当我尝试提供下拉菜单时。默认情况下,我需要选择一个需要显示的值。当我不使用 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>
- 使用的属性。已选择
<option *ngFor="let type of ListType" [ngValue]="type " [attr.selected]="type .name== type.name ? true : null">{{ type.name }}</option>
编辑
- 即使试图通过模型设置选定的值仍然没有结果。
还有其他方法吗?或者我做错了什么?
原文由 Abhishek Ekaanth 发布,翻译遵循 CC BY-SA 4.0 许可协议
You are defining the value for the
select
as theid
value, whereas you are feeding theselectedListType
with thename
property.因此,您要做的是提供id
的值selectedListType
,例如,如果您的ListType
看起来像这样:您要将
selectedListyType
值设置为1
。另一种选择是,如果您不知道您可以执行的 id 值:然后您的模板将如下所示: