【发布时间】: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