Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select list set selected item angular 2 ngModel

This is my current code:

<select name="role" [(ngModel)]="user.role">
    <option *ngFor="let role of roles" [ngValue]="role" [attr.selected]="role == user.role ? 'true' : 'false'">{{role.name}}</option>
</select>

I'm loading all the roles in an array, and the user class has a Role attribute (which is not loaded like user.role = roles[0] but just through the backend data).

The problem is that the selected attribute is not working, and my select is not going to the correct role. What am I doing wrong?

like image 684
JDOE Avatar asked Feb 14 '17 11:02

JDOE


2 Answers

Just remove

[attr.selected]="role == user.role ? 'true' : 'false'"

and assign the selected role to user.role and ngModel will make the matching item the selected one.

If the role is an object, the assigned instance needs to be identical.

See also the recently added custom comparison https://github.com/angular/angular/issues/13268 available since 4.0.0-beta.7

<select [compareWith]="compareFn" ...
compareFn(val1, val2): boolean {
  return val1 && val2 ? val1.id === val2.id : val1 === val2;
}
like image 94
Günter Zöchbauer Avatar answered Nov 10 '22 06:11

Günter Zöchbauer


You don't need to use [attr.selected]. [(ngModel)]="user.role" is two-way data-binding, it will select the matched option from your list if value is equal to user.role. And you can also use basic [value]

<select name="role" [(ngModel)]="user.role">
    <option *ngFor="let role of roles" [value]="role">{{role.name}}</option>
</select>
like image 3
Suren Srapyan Avatar answered Nov 10 '22 06:11

Suren Srapyan