我有一个页面,允许用户更新汽车的颜色 . 有两个api调用,一个用于返回汽车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
}
这是一个显示问题的掠夺者 . 只需在这些线之间切换即可说明问题 .
this.car.colour = this.colours [1]; //工作
this.car.colour = new Color(1,'Green'); //失败
https://plnkr.co/edit/m3xBf8Hq9MnKiaZrjAaI?p=preview
当以这种方式绑定时,如何通过值比较对象来比较对象而不是引用?
问候
史蒂夫
Update
我通过将模型的“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];
});
});
}
2 回答
那是设计的 . Angular2仅比较对象引用,而不是对象的属性 .
您可以绑定到原始值,然后compairson按预期工作
假设
Color
具有包含字符串Green
的属性name
.您也可以通过在颜色中查找
car.colour
并从表示相同颜色的颜色将car.colour
设置为Colour
实例来自行完成比较 .您可以使用以下内容
当选定的值将被更新时,您将在someFunction中处理此问题