Use Case: Ich habe ein Multiple Select-Element mit 6 Farben. Ich brauche 2 dieser ausgewählten Farben. Vielen Dank. Unten ist mein Code, aber etwas stimmt nicht?Angular2 Multiple Select-Element muss einige ausgewählte haben
Wenn es eine bessere Möglichkeit gibt, dies zu tun, bitte teilen?
//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;
}
}
Sie können festlegen, welches Problem Sie mit diesem Code konfrontiert sind und was Sie haben versucht, es zu lösen. –
Alles funktioniert, aber meine Farben sind nicht ausgewählt. – Mark
Ist das wonach Sie suchen? – RemyaJ