Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2: how bind to select multiple

Tags:

angular

I'm able to bind using ngModel for a single select but I would like to bind an array to the multiple selected options. When I attempt this I get the error

Cannot find a differ supporting object 'xxx' in 'myModelProperty'

My Code

<select multiple [(ngModel)]="myModelProperty">     <option *ngFor="#item of myOptions" [value]="item.value">{{item.name}}</option> </select> 
like image 795
Honorable Chow Avatar asked Feb 03 '16 02:02

Honorable Chow


1 Answers

Why all those complicate answers about simple question.

If you in advance have options which have to be selected, you can do it simply this way :

This code is good :

HTML

<select multiple [(ngModel)]="myModelProperty">     <option *ngFor="#item of myOptions" [value]="item.value">{{item.name}}</option> </select> 

ANGULAR

myModelProperty: any; myModelProperty = ['YOUR_VALUE', 'YOUR_VALUE']; 

or if you have string, you can parse it

myModelProperty: any; myModelProperty = string.split(','); 

So, all you have to done is that [(ngModel)] from select tag, have to be initialized in angular part with some array of values which correspond to [value] from option tag

This will automatically select one or more options depends on values from array.

like image 200
Nebojsa Sapic Avatar answered Oct 05 '22 18:10

Nebojsa Sapic