angular - Angular mat-select value 2 way 使用对象的数据绑定
问题描述
在 Angular html 模板中,我有一个带有 mat-select 指令(Angular Material)的选择元素,它从存储在服务 .ts 文件中名为“selectedCriteria”的属性中的对象加载数据。根据应用程序逻辑,“selectedCriteria”属性中可以存储三种类型的对象,它们都具有String类型的“name”变量。所以我想在这个选择元素中加载对象名称。问题是当应用程序加载时,选择元素不会加载/显示“selectedCriteria”,因为它是一个对象而不是字符串。我可以使用 selectedCriteria.name 将其与字符串值绑定,但这将添加额外的代码以从对象转换为字符串,反之亦然,用于双向数据绑定。在应用程序启动期间在此选择元素中加载对象的解决方案是什么?
<mat-form-field style="width: 45%; display: inline-block">
<mat-select placeholder="Criteria" [(value)]="reportService.selectedCriteria" (valueChange)="reportService.filterSalesData()">
<mat-option *ngFor="let criteria of reportService.criteriaList" [value]="criteria">{{criteria.name}}</mat-option>
</mat-select>
</mat-form-field>
解决方案
您可以按如下方式执行此操作。
HTML
<mat-form-field style="width: 45%; display: inline-block; margin-right: 40px;">
<mat-select [(ngModel)]="selectedCriteria" (selectionChange)="onSelectValueChange()">
<mat-option *ngFor="let criteria of criteriaList" [value]="criteria">{{criteria.name}}</mat-option>
</mat-select>
</mat-form-field>
TS
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
selectedCriteria: User;
criteriaList: User[] = [
{ name: 'John Doe'},
{ name: 'Albert Einstein'},
{ name: 'Isaac Newton'}
];
ngOnInit(){
this.selectedCriteria = this.criteriaList[0];
}
onSelectValueChange () {
console.log(this.selectedCriteria);
console.log('Type of Selection => ', typeof this.selectedCriteria);
}
}
interface User{
name: string;
}
推荐阅读
- scala - 用于安装 scala 插件的 URL 损坏
- ios - 适用于 iOS 的 Firebase Crashlytics:关闭非符号化问题
- c# - 实体框架 - 按实体或表进行通用审计
- javascript - Jquery .each() .click() 只获取最后一个元素中的数据
- python - Matplotlib boxplot:conf_intervals 长度与 x 不兼容
- mysql - 在无脂肪框架中运行准备好的语句
- php - mysql join where for 1 table
- java - 如果抛出运行时异常,Hibernate 不会回滚
- proxy - BrowserSync 代理卡住加载
- java - 以 16 字节为单位的过程数据