您如何在 *ngfor中的垫子选择中设置默认值
我正在尝试在 *ngfor中设置一个默认值,但是,从环路中访问数组中的元素无法正常工作。这种方法有类似的方法吗?
.ts文件:
persons: Person[] = .. //consist of Person with name and age
.html文件:
<div *ngFor="let person of persons">
{{ person.name }}
<mat-form-field>
<mat-select [(value)]="person.age">
<mat-option value="10-20">10-20</mat-option>
<mat-option value="20-30">20-30</mat-option>
</mat-select>
</mat-form-field>
</div>
I am trying to set a default value in mat-select within an *ngFor, however, accessing the element in the array from the loop is not working as wanted. Is there any similar way to this approach?
.ts file:
persons: Person[] = .. //consist of Person with name and age
.html file:
<div *ngFor="let person of persons">
{{ person.name }}
<mat-form-field>
<mat-select [(value)]="person.age">
<mat-option value="10-20">10-20</mat-option>
<mat-option value="20-30">20-30</mat-option>
</mat-select>
</mat-form-field>
</div>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要设置默认值,您需要使用分配给每个对象的
age
属性的值填充数组。然后MAT-SELECT
[(value)]
绑定可以将匹配值设置为默认值。示例( stackblitz demo ):
如果您的数组是动态的,则可以运行一个循环以将默认值分配给每个元素。
html:
结果:
To set a default value, you need to populate your array with a value assigned to each object's
age
property. Thenmat-select
[(value)]
binding can set the matching value as default.Example (Stackblitz demo):
If your array is dynamic, you can run a loop to assign a default value to each element as well.
html:
Result: