角材料:垫选择不选择默认 [英] Angular Material: mat-select not selecting default
问题描述
我有一个mat-select选项,其中选项是数组中定义的所有对象.我正在尝试将值默认设置为选项之一,但是在页面呈现时仍处于选中状态.
I have a mat-select where the options are all objects defined in an array. I am trying to set the value to default to one of the options, however it is being left selected when the page renders.
我的打字稿文件包含:
public options2 = [
{"id": 1, "name": "a"},
{"id": 2, "name": "b"}
]
public selected2 = this.options2[1].id;
我的HTML文件包含:
My HTML file contains:
<div>
<mat-select
[(value)]="selected2">
<mat-option
*ngFor="let option of options2"
value="{{ option.id }}">
{{ option.name }}
</mat-option>
</mat-select>
</div>
我尝试将selected2
和value
在mat-option
中设置为对象及其ID,并且尝试在mat-select
中同时使用[(value)]
和[(ngModel)]
,但是没有一个工作.
I have tried setting selected2
and the value
in mat-option
to both the object and it's id, and have tried using both [(value)]
and [(ngModel)]
in the mat-select
, but none are working.
我正在使用材料版本2.0.0-beta.10
I am using material version 2.0.0-beta.10
推荐答案
为模板中的值使用绑定.
Use a binding for the value in your template.
value="{{ option.id }}"
应该是
[value]="option.id"
然后在您选择的值中使用ngModel
而不是value
.
And in your selected value use ngModel
instead of 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起 a> 材料选择现在接受mat-form-field
元素作为父元素,因此与其他物料输入控件一致.升级后,将div
元素替换为mat-form-field
元素.
On a side note as of version 2.0.0-beta.12 the material select now accepts a mat-form-field
element as the parent element so it is consistent with the other material input controls. Replace the div
element with mat-form-field
element after you upgrade.
<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>
这篇关于角材料:垫选择不选择默认的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!