Angular Material:mat-select 不选择默认 [英] Angular Material: mat-select not selecting default
问题描述
我有一个 mat-select,其中的选项是在数组中定义的所有对象.我正在尝试将该值设置为默认选项之一,但是在页面呈现时它仍处于选中状态.
我的打字稿文件包含:
公共选项 2 = [{"id": 1, "name": "a"},{"id": 2, "name": "b"}]public selected2 = this.options2[1].id;
我的 HTML 文件包含:
<mat-select[(value)]="selected2"><mat-option*ngFor="让 options2 的选项"value="{{ option.id }}">{{ option.name }}</mat-option></mat-select>
我尝试将 selected2
和 mat-option
中的 value
设置为对象和它的 id,并尝试同时使用 <mat-select
中的 code>[(value)] 和 [(ngModel)]
,但都没有工作.
我使用的是材料版本 2.0.0-beta.10
对模板中的值使用绑定.
value="{{ option.id }}"
应该是
[value]="option.id"
并在您选择的值中使用 ngModel
而不是 value
.
应该是
完整代码:
<mat-select [(ngModel)]="selected2"><mat-option *ngFor="let option of options2" [value]="option.id">{{ option.name }}</mat-option></mat-select>
<小时>
附注 2.0.0-beta.12 版 材料选择 现在接受 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>
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.
My typescript file contains:
public options2 = [
{"id": 1, "name": "a"},
{"id": 2, "name": "b"}
]
public selected2 = this.options2[1].id;
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>
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.
I am using material version 2.0.0-beta.10
Use a binding for the value in your template.
value="{{ option.id }}"
should be
[value]="option.id"
And in your selected value use ngModel
instead of value
.
<mat-select [(value)]="selected2">
should be
<mat-select [(ngModel)]="selected2">
Complete code:
<div>
<mat-select [(ngModel)]="selected2">
<mat-option *ngFor="let option of options2" [value]="option.id">{{ option.name }}</mat-option>
</mat-select>
</div>
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>
这篇关于Angular Material:mat-select 不选择默认的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!