选定的属性不起作用,除非它是数组中的最后一项



我有一个表单,我想根据某些条件默认选择项目。我有一个数组 (myList(,其中包含用于填充选择列表的项目和一个来自后端 api 的变量 (myItem(,我希望我的所选值是 myItem,但这仅在 myItem 是数组中的最后一个项目时才有效。

所以这不起作用(没有默认选择的项目(

this.myList = ['Dave', 'Jerry', 'Sam']
this.myItem = 'Jerry'
<*ngFor="let list of myList" [ngValue]="list" [selected]="list === myItem">{{list}}</option> 
but this would work
this.myList = ['Dave', 'Jerry', 'Sam']
this.myItem = 'Sam'
<*ngFor="let list of myList" [ngValue]="list" [selected]="list === myItem">{{list}}</option> 

如果有人告诉我为什么会发生这种情况,我会很高兴。

谢谢

绑定<select>元素的方法与绑定元素的方法<input>方法相同。如果使用 ngModel 绑定<input>元素,则选择应如下所示:

<select [(ngModel)]="myItem" ... other attributes ...>
<option *ngFor="let option of myList">{{option}}</option>
</select>

最新更新