【问题标题】:Dropdown list - model binding by value - angular 2下拉列表 - 按值绑定模型 - 角度 2
【发布时间】:2016-10-27 08:38:13
【问题描述】:

我有一个允许用户更新汽车颜色的页面。有两个 api 调用,一个用于返回 car json 对象,一个用于填充颜色的下拉列表。

我的问题是 Angular 2 似乎是通过引用而不是值进行模型绑定。这意味着,尽管可能在汽车上设置了“绿色”颜色,但即使它匹配,也不会在下拉列表中选择“绿色”颜色,因为该对象来自不同的 api 调用。

这里选择列表绑定到汽车的“颜色”属性。

<div>
    <label>Colour</label> 
    <div>
        <select [(ngModel)]="car.colour">     
            <option *ngFor="let x of colours" [ngValue]="x">{{x.name}}</option>
        </select> 
    </div>
</div>

当我在后端设置模型时,如果我将汽车的颜色设置为具有相同的值对象(在本例中为绿色),则不会选择下拉菜单。但是,当我使用用于绑定列表的值列表中的相同实例设置它时,它会按预期选择。

  ngOnInit(): void {

        this.colours = Array<Colour>();
        this.colours.push(new Colour(-1, 'Please select'));
        this.colours.push(new Colour(1, 'Green'));
        this.colours.push(new Colour(2, 'Pink'));

        this.car = new Car();
        //this.car.colour = this.colours[1]; // Works
        this.car.colour = new Colour(1, 'Green');  // Fails    
    }

这是一个显示问题的 plunker。只需在这几行之间切换即可说明问题。

this.car.colour = this.colours[1]; // 工作

this.car.colour = new Colour(1, 'Green'); //失败

https://plnkr.co/edit/m3xBf8Hq9MnKiaZrjAaI?p=preview

当以这种方式绑定时,如何获得角度来比较对象的值而不是引用?

问候

史蒂夫

更新

我通过将模型“superPower”属性设置为用于填充下拉列表的列表中的匹配项来解决我的用例。

setupUpdate(id: number): void {

    this.pageMode = PageMode.Update;
    this.submitButtonText = "Update";

    this.httpService.get<Hero>(this.appSettings.ApiEndPoint + 'hero/' + this.routeParams.get('id')).subscribe(response => { 
        this.hero = response;             

        this.httpService.get<SuperPower[]>(this.appSettings.ApiEndPoint + 'superPower/').subscribe(response => {
            this.superPowers = response;   
            this.hero.superPower = this.superPowers.filter(x => x.id == this.hero.superPower.id)[0];
        });
    });
}

【问题讨论】:

    标签: javascript angular angular2-forms


    【解决方案1】:

    这是设计的。 Angular2 只比较对象引用,而不比较对象的属性。

    您可以绑定到原始值,然后比较按您的预期工作

        <select [(ngModel)]="car.colour.name">     
            <option *ngFor="let x of colours" [value]="x.name">{{x.name}}</option>
        </select> 
    

    假设Color 的属性name 包含字符串Green

    您也可以通过在颜色中查找car.colour 并将car.colour 设置为代表相同颜色的颜色中的Colour 实例来自己进行比较。

    【讨论】:

    • 使用 'value' 而不是 'ngValue' 意味着验证指令在下拉列表中不起作用。我将不得不使用它会出现的断开连接的模型。谢谢。
    【解决方案2】:

    你可以使用下面的

    <select [(ngModel)]="car.colour.name" (ngModelChange)="someFunction($event)" >     
        <option *ngFor="let x of colours" [value]="x.name">{{x.name}}</option>
    </select> 
    

    将更新所选值时,您将在某种函数

    中处理此操作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-21
      • 2018-02-16
      相关资源
      最近更新 更多