I have an array of objects (named users ) that will display as dropdownlist options. and I have a list of other objects (named selectedUsers and saved in the backend) that is used to initialize the dropdownlist .
array:
users = [ { id: 2, name: 'name2' },{ id: 2, name: 'name2' },{ id: 3, name: 'name3' } ]; selectedUsers3 = [ { id: 1, name: 'name1' },{ id: 2, name: 'name2' } ];
I came across a wired situation where I bind Object to select options to [ngValue] and bind a function to [selected] , which checks if the current option exists in selectedUsers .
I see that the function is being extracted, and the result is returned true / false as excluded, but the parameters remain unselected.
template:
<select multiple [(ngModel)]="selectedUsers3"> <option *ngFor="let user of users" [selected]="checkExist(user)" [ngValue]="user">{{user.name}}</option> </select>
in component:
checkExist(user) { return this.selectedUsers3.findIndex(selUser => selUser.id === user.id) > -1;
mention that I used Array.filter or Array.findIndex to check if data exists and the correct result.
Please refer to the demo with the third dropdownlist and check where I am doing something wrong? or am I missing something about [selected] ? Hope someone can explain this.
UPD:
with @ Günter Zöchbauer help, this situation can be resolved using the compareWith directive (see his answer) regardless of single select or multi select , but I'm still confused about why they work well together, but fail together and still trying to figure out reason.
source share