gpt4 book ai didi

javascript - 下拉列表 - 按值绑定(bind)模型 - angular 2

转载 作者:行者123 更新时间:2023-11-29 17:57:12 24 4
gpt4 key购买 nike

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

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

此处选择列表绑定(bind)到汽车的“颜色”属性。

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

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

  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 显示了这个问题。只需在这些 to 行之间切换即可说明问题。

this.car.colour = this.colours[1];//有效

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

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

当以这种方式绑定(bind)时,我如何获得 Angular 来按值而不是引用来比较对象?

问候

史蒂夫

更新

我通过将模型的“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];
});
});
}

最佳答案

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

您可以绑定(bind)到原始值,然后 compairson 按您预期的方式工作

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

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

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

关于javascript - 下拉列表 - 按值绑定(bind)模型 - angular 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38018252/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com