Angular 2: Select dropdown not selecting option despite “selected” attribute

巧了我就是萌 提交于 2019-12-12 12:32:46

问题


I have the following code for a select dropdown:

<select id="UnitOfMeasurementId" name="UnitOfMeasurementId" [(ngModel)]="UnitOfMeasurementId">
    <option *ngFor="let unit of UnitOfMeasurements" [ngValue]="unit.Value" [selected]="unit.Selected">{{unit.Text}}</option>
</select>

Each item in the UnitOfMeasurements array looks something like this:

Selected: false
Text: "lb"
Value: "1"

Or this:

Selected: true
Text: "kg"
Value: "3"

[(ngModel)]="UnitOfMeasurementId" contains the value of the item that should be selected. In this particular example, that value is 3, so the 3rd item should be selected. Sure enough, when I inspect the element it shows ng-reflect-selected="true" on the correct item, but nothing is actually selected. How can I get the correct item in the list to actually dynamically select instead of just adding the ng-reflect-selected="true" attribute?


回答1:


Don't use the selected attribute with ngModel and ngValue, but instead assign the value of the selected item to UnitOfMeasurementId.

It's important that it has the identical instance as the one used in *ngFor. Some other object instance with the same properties and same values won't work.




回答2:


attr.selected binding sets attribute value to the passed value. So if you pass false it will set selected="false" which is not what you want to get (as it makes element actually selected according to HTML spec). To remove attribute you have to pass null.

Use:

[attr.selected]="unit.Selected ? '' : null"



来源:https://stackoverflow.com/questions/40730700/angular-2-select-dropdown-not-selecting-option-despite-selected-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!