angular - Angular2: how bind to select multiple -


i'm able bind using ngmodel single select bind array multiple selected options. when attempt error

cannot find differ supporting object 'xxx' in 'mymodelproperty'

my code

<select multiple [(ngmodel)]="mymodelproperty">     <option *ngfor="#item of myoptions" [value]="item.value">{{item.name}}</option> </select> 

here's multi-select list implementation supports two-way databinding. use @viewchild instead of getelementbyid().

@component({   selector: 'my-app',   template: `{{title}}<p>   <select #select multiple (change)="change($event.target.options)">     <option *ngfor="#item of myoptions" [value]="item.value">       {{item.name}}     </option>   </select>   <br><button (click)="changeoptions()">select 1 , 3</button>   <p>{{selectedvalues | json}}` }) export class appcomponent {   @viewchild('select') selectelref;   title = "angular 2 beta - multi select list";   myoptions = [      {value: 1, name: "one"},      {value: 2, name: "two"},     {value: 3, name: "three"}];   selectedvalues = ['1','2'];   mymodelproperty = this.myoptions[0];   constructor() { console.clear(); }   ngafterviewinit() {     this.updateselectlist();   }   updateselectlist() {     let options = this.selectelref.nativeelement.options;     for(let i=0; < options.length; i++) {       options[i].selected = this.selectedvalues.indexof(options[i].value) > -1;     }   }   change(options) {     this.selectedvalues = array.apply(null,options)  // convert real array       .filter(option => option.selected)       .map(option => option.value)   }   changeoptions() {     this.selectedvalues = ['1','3'];     this.updateselectlist();   } } 

plunker

whenever selectedvalues property changed component logic, updateselectlist() must called, shown in "select 1 , 3" button callback logic.

for easier reuse, should refactored attribute directive. (any takers?)


Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -