当我在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>
结果=&gt;
<option value="0: '1'">me</option>
<option value="1: '2'">you</option>
Angular将数组中对象的索引预先添加到options标记的值。反正有没有阻止这种行为?
答案 0 :(得分:0)
好的,我最终得到了自定义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>
答案 1 :(得分:0)
使用[ngValue]
代替[value]
。
<select [(ngModel)]="model" multiple>
<option *ngFor="let o of options" [ngValue]="o.id"> {{o.name}} </option>
</select>