【问题标题】:Angular multi attribute on select tag alters the value of the option tags选择标签上的角度多属性改变了选项标签的值
【发布时间】:2017-05-15 14:23:06
【问题描述】:

当我在 select 标签上使用 multiple 属性时,Angular 会改变 option 标签的值。例如:

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 将数组中对象的索引添加到选项标签的值之前。有没有办法阻止这种行为?

【问题讨论】:

  • 你用的是什么版本的angular?
  • @Leguest Angular 2.4.5
  • 这是因为multiple 属性。所以value="1: '2'" 不会影响[(ngModel)]="model" 无论如何都会是[1,2]
  • @Leguest,我知道这一点,但有什么办法可以阻止这种行为。我需要在 DOM 中正确的值

标签: javascript html angular tags


【解决方案1】:

好的,我最终得到了自定义 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>

【讨论】:

【解决方案2】:

使用[ngValue] 代替[value]

<select [(ngModel)]="model" multiple>
  <option *ngFor="let o of options" [ngValue]="o.id"> {{o.name}} </option>
</select>

【讨论】:

    猜你喜欢
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-08
    • 1970-01-01
    • 1970-01-01
    • 2020-02-19
    相关资源
    最近更新 更多