angular - Angular2 multiple Select element needs to have a few selected -


use case: have multiple select element 6 colors. need 2 of colors selected. much. below code, not right?

if there better way of doing this, please share?

//view <select name="wrcolors" #wrcolors [(ngmodel)]="selectedcolors" multiple >   <option *ngfor="let color of allcolors" [ngvalue]="color">{{color.label}</option> </select>  //component allcolors = [{   id: 1,   label: 'red', }, {   id: 2,   label: 'blue', }, {   id: 3,   label: 'green', }, {   id: 4,   label: 'yellow', }, {   id: 5,   label: 'orange', }, {   id: 6,   label: 'purple', }];  selectedcolors = [{   id: 2,   label: 'blue', }, {   id: 4,   label: 'yellow', }];  @viewchild('wrcolors') selectcolorref: elementref;  ngafterviewinit(): void {   this.updateselectlist(); }  updateselectlist() {     let options = this.selectcolorref.nativeelement.options;      (let = 0; < this.allcolors.length; i++) {          (let n = 0; n < this.selectedcolors.length; n++) {             if (this.selectedcolors[n].id === this.allcolors[i].id) {                  options[i].selected = true;              }         }          //options[i].selected = this.selectedcolors.indexof(options[i].value) > -1;     } } 

this.preselectedids = this.selectedarr.map(obj =>{   return obj.id; }); //mark this.preselectedids = this.selectedarr.map(function (a:any) { return a.id; });   in option tag inside ngfor,  [attr.selected]="preselectedids.indexof(color.id)!=-1 ? true: false" 

Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -