当我在select标签上使用multiple属性时,Angular会改变选项标签的值。例如:
this.options = [
{ id: 1, name: 'me' },
{ id: 2, name: 'you' }
];
<select [(ngModel)]="model" multiple>
<option *ngFor="let o of options" [value]="o.id"> {{o.name}} </option>
</select>
结果=>
<option value="0: '1'">me</option>
<option value="1: '2'">you</option>
Angular将数组中对象的索引预先设置为options标记的值。反正有没有阻止这种行为?
好的,我最终定制了directive
。我把它称为multipleNormalize
并像[multipleNormalize]="o.id"
一样使用它
打字稿
import {Directive, ElementRef} from '@angular/core';
import {Input} from '@angular/core';
@Directive({
selector: '[multipleNormalize]',
})
export class MultipleNormalizeDirective {
@Input('multipleNormalize') model:any;
constructor(private elementRef:ElementRef) {
}
ngOnInit(): void {
this.elementRef.nativeElement.value = this.model;
}
}
HTML
<select [(ngModel)]="testModel" multiple>
<option *ngFor="let o of optionItems" [ngValue]="o.id" [multipleNormalize]="o.id">{{o.name}}</option>
</select>
使用[ngValue]
而不是[value]
。
<select [(ngModel)]="model" multiple>
<option *ngFor="let o of options" [ngValue]="o.id"> {{o.name}} </option>
</select>