当我尝试提供下拉菜单时。默认情况下,我需要选择一个需要显示的值。当我不使用 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>
- 使用 attr.Selected
<option *ngFor="let type of ListType" [ngValue]="type " [attr.selected]="type .name== type.name ? true : null">{{ type.name }}</option>
编辑
- 甚至尝试通过模型设置所选值仍然没有结果。
还有其他方法吗? 或者 我做错了什么吗?
最佳答案
您正在将 select
的值定义为 id
值,而您正在为 selectedListType
提供 name
属性。因此,您要做的是为 selectedListType
提供 id
值,例如,如果您的 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>
关于html - Angular 4 Selected 在模型中给出时无法正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48003432/