Use Case: I have a multiple Select element with 6 colors. I need 2 of those colors selected. Thanks much. Below is my code, but something is not right?
If there is a 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;
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;
}
}