Angular2多个Select元素需要选择一些

时间:2017-04-07 14:56:11

标签: angular

用例:我有一个包含6种颜色的多个Select元素。我需要选择2种颜色。非常感谢。下面是我的代码,但有些事情不对吗?

如果有更好的方法,请分享?

//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;

    for (let i = 0; i < this.allColors.length; i++) {

        for (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;
    }
}

1 个答案:

答案 0 :(得分:0)

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"