select标记上的Angular multi属性会更改选项标记的值

问题描述 投票:0回答:2

当我在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标记的值。反正有没有阻止这种行为?

javascript html html5 angular tags
2个回答
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>

0
投票

使用[ngValue]而不是[value]

<select [(ngModel)]="model" multiple>
  <option *ngFor="let o of options" [ngValue]="o.id"> {{o.name}} </option>
</select>
© www.soinside.com 2019 - 2024. All rights reserved.