I have an array of objects(named users) which will be shown as options of dropdownlist
. and I have another objects list(named selectedU
selected
is not supported with [(ngModel)]="selectedUser3"
.
To make an item selected, the value
(for string only) or ngValue
property value needs to match the value in selectedUser3
.
this.selectedUser3 = this.users[2];
By default only object identity is checked, therefore another object instance with the same properties and values doesn't match.
You can customize comparison using compareWith
https://angular.io/docs/ts/latest/api/forms/index/SelectControlValueAccessor-directive.html
<select [compareWith]="compareFn" [(ngModel)]="selectedCountries"> <option *ngFor="let country of countries" [ngValue]="country"> {{country.name}} </option> </select> compareFn(c1: Country, c2: Country): boolean { return c1 && c2 ? c1.id === c2.id : c1 === c2; }
Answer to conflicts between [(ngModel)] and [selected]
after some research and debug, I find that while using ngModel
on select
, angular will run it's own SelectMultipleControlValueAccessor for select
and own directive for option
of select
which lead selected
to be ignored.
In the third example(example plunker), after ngModel
is used, although function bind to [selected]
will be called, but it's result is simply ignored.
Comments
[(ngModel)]
and [ngValue]
with same instance of objects.compareWith
directive, see Gunter' s anwseroption
.New Info:
See also this issue for more information.