Angular 2: select the drop-down list without selecting an option, despite the "selected" attribute

I have the following code for a drop down list:

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

Each element of the UnitOfMeasurements array looks something like this:

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

Or that:

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

[(ngModel)]="UnitOfMeasurementId" contains the value of the item to be selected. In this particular example, this value is 3, so you need to select the 3rd element. Of course, when I check an element, it shows ng-reflect-selected="true" on the correct element, but nothing is selected. How can I get the correct item in the list for actual dynamic selection instead of adding the ng-reflect-selected="true" attribute?

+3
source share
2 answers

Do not use the selected attribute with ngModel and ngValue , but instead assign the value of the selected UnitOfMeasurementId element.

It is important that it has the identical instance that was used in *ngFor . Some other instances of objects with the same properties and the same values โ€‹โ€‹will not work.

+4
source

attr.selected binds the attribute value to the passed value. Therefore, if you pass false , it will set selected="false" , which is not what you want to get (since it actually selects the element according to the HTML specification). To remove an attribute, you must pass null .

Using:

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

+5
source

Source: https://habr.com/ru/post/1268910/


All Articles