【发布时间】:2017-04-08 00:10:07
【问题描述】:
用例:我有一个具有 6 种颜色的多个 Select 元素。我需要选择其中两种颜色。非常感谢。下面是我的代码,但有什么不对吗?
如果有更好的方法,请分享?
//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;
}
}
【问题讨论】:
-
您可以指定该代码面临的问题以及您尝试解决的问题。
-
一切正常,但没有选择我的颜色。
-
这是您要找的吗?
标签: angular