【发布时间】:2017-11-02 10:30:43
【问题描述】:
我在 Angular 4 ngModel 中发现了有趣的错误。 组件:
this.restService.getProduct(this._id).subscribe(
response => {
this.product = response;
this.productCategory = response.category;
...
模板:
<select [(ngModel)] = "productCategory._id" class="form-control form-
control-sm" id="category">
<option *ngFor="let category of existedCategories | orderBy: 'name'"
value="{{category._id}}">{{category.name}}</option>
</select>
当我在模板中更改 productCategory._id 的 ngModel 值时,this.product.category._id 的值也会发生变化。而这个检查返回 false:
if (this.product.category._id !== this.productCategory._id) {
observables.push(
this.restService.changeProductCategory(this.product.category._id,
this.productCategory._id, this.product._id));
}
我找到了一些绕过这个的解决方案:
this.restService.getProduct(this._id).subscribe(
response => {
this.product = response;
const resp = JSON.parse(JSON.stringify(response));
this.productCategory = resp.category;
但还是不明白为什么会这样。
【问题讨论】:
-
如果这是您想要的,那么您将数据绑定到错误的属性。
[(ngModel)] = "productCategory._id"绑定到this.productCategory._id,你可以绑定到product.category._id
标签: angular