当我试图提供下拉菜单时。默认情况下,我需要选择一个需要显示的值。当我不使用 ngModel 时,我可以显示默认值。
没有 ngModel
<select class="form-control">
<option *ngFor="let type of ListType" [value]="type .id">{{type .name}}</option>
</select>
当我们编译上面的代码时,它可以正常工作。我可以看到要显示的列表中的第一个值。
使用 ngModel
<select class="form-control" [(ngModel)]="selectedListType">
<option *ngFor="let type of ListType" [value]="type .id">{{type .name}}</option>
</select>
这是显示为空。
尝试过的方法:
- 二手 已选
<option *ngFor="let type of ListType" [selected]="type.name === 'Dislike'" [value]="type .id">{{type .name}}</option>
- 使用的属性.Selected
<option *ngFor="let type of ListType" [ngValue]="type " [attr.selected]="type .name== type.name ? true : null">{{ type.name }}</option>
EDIT
- 即使尝试通过模型设置所选值仍然没有结果。
还有其他方法吗?
或者
难道我做错了什么?
您正在定义的值select
as the id
值,而你正在喂养selectedListType
与name
财产。所以你想要做的就是提供id
价值selectedListType
,例如如果你的ListType
看起来像这样:
[{id:1, name: 'Dislike'},{...}]
你想设置selectedListyType
价值为1
。另一种选择是,如果您不知道 id 值,您可以执行以下操作:
ngOnInit() {
this.selectedListType = this.ListType.find(x => x.name === 'Dislike').id
}
然后你的模板将如下所示:
<select class="form-control" [(ngModel)]="selectedListType">
<option *ngFor="let type of ListType" [value]="type.id">{{type.name}}</option>
</select>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)