我有一个mat-select,其中的选项都是定义在一个数组中的对象。 我试图将值设置为默认的选项之一,但是当页面渲染时,它被留在了选择区。
我的typescript文件包含。
public options2 = [
{"id": 1, "name": "a"},
{"id": 2, "name": "b"}
]
public selected2 = this.options2[1].id;
我的HTML文件中包含。
<div>
<mat-select
[(value)]="selected2">
<mat-option
*ngFor="let option of options2"
value="{{ option.id }}">
{{ option.name }}
</mat-option>
</mat-select>
</div>
我试着把selected2
和mat-option
中的value
设置为对象和它的id,并试着在mat-select
中使用[(value)]
和[(ngModel)]
,但都没有作用。
我使用的是2.0.0-beta.10版的材料。
在你的模板中使用一个绑定的值。
value="{{ option.id }}"
应该是
[value]="option.id"
在你的选择值中使用ngModel
而不是value
。
<mat-select [(value)]="selected2">
应该是
<mat-select [(ngModel)]="selected2">
完整的代码。
<div>
<mat-select [(ngModel)]="selected2">
<mat-option *ngFor="let option of options2" [value]="option.id">{{ option.name }}</mat-option>
</mat-select>
</div>
顺便提一下,从2.0.0-beta.12版开始,material select现在接受mat-form-field
元素作为父元素,这样它就和其他材料输入控件一致。升级后用mat-form-field
元素替换div
元素。
<mat-form-field>
<mat-select [(ngModel)]="selected2">
<mat-option *ngFor="let option of options2" [value]="option.id">{{ option.name }}</mat-option>
</mat-select>
</mat-form-field>
我使用Angular 5和带有mat-select的reactive forms,无法让上述两种解决方案显示初始值。
我不得不添加[compareWith]来处理在mat-select组件中使用的不同类型。在内部,似乎mat-select使用一个数组来保存选择的值。如果该模式被打开,这可能允许相同的代码在多个选择中工作。
这是我的解决方案。
用表单生成器来初始化表单控件。
this.formGroup = this.fb.group({
country: new FormControl([ this.myRecord.country.id ] ),
...
});
然后在你的组件上实现compareWith函数。
compareIds(id1: any, id2: any): boolean {
const a1 = determineId(id1);
const a2 = determineId(id2);
return a1 === a2;
}
接下来创建并导出 determineId 函数(我不得不创建一个独立的函数,以便mat-select可以使用它)。
export function determineId(id: any): string {
if (id.constructor.name === 'array' && id.length > 0) {
return '' + id[0];
}
return '' + id;
}
最后给你的mat-select添加compareWith属性。
<mat-form-field hintLabel="select one">
<mat-select placeholder="Country" formControlName="country"
[compareWith]="compareIds">
<mat-option>None</mat-option>
<mat-option *ngFor="let country of countries" [value]="country.id">
{{ country.name }}
</mat-option>
</mat-select>
</mat-form-field>
你应该在 "mat-option "中把它绑定为"[value]",如下所示。
<mat-select placeholder="Panel color" [(value)]="selected2">
<mat-option *ngFor="let option of options2" [value]="option.id">
{{ option.name }}
</mat-option>
</mat-select>