5

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?

JDOE
  • 67
  • 2
  • 5

3 Answers3

6

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;
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Thank you, makes sense that it doesn't work since the objects are not the same reference. Can I use a `ngComparator` for this? Or what would be the syntax? – JDOE Feb 14 '17 at 13:36
  • I updated my answer. It should be included in 4.0.0-beta.7 – Günter Zöchbauer Feb 14 '17 at 14:52
  • Just one question, did you test this out? I tried it but couldn't get it to work with the `[compareWith]` function. Apparently my `val2` is always null =/ – JDOE Feb 16 '17 at 11:16
  • Are you using Angular 4.0.0-beta.7? I haven't tested it, but the code is from an example in the linked PR, from the guy who implemented this feature. – Günter Zöchbauer Feb 16 '17 at 11:17
3

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>
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
0
<select [ngModel]="selectedDevice" (ngModelChange)="onChange($event)" name="sel2">
    <option [value]="i" *ngFor="let i of devices">{{i}}</option>
</select>

onChange(newValue) {
    console.log(newValue);
    this.selectedDevice = newValue;\
}
Yoav Schniederman
  • 5,253
  • 3
  • 28
  • 32