【问题标题】:Why Angular 4 ngModel changes another variables?为什么 Angular 4 ngModel 会改变另一个变量?
【发布时间】: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


【解决方案1】:

因为 productCategory 与 product.category 在内存中引用的位置相同。

这不是 Angular 4 的错误。这就是引用类型的工作方式。我附上学习链接:https://codeburst.io/explaining-value-vs-reference-in-javascript-647a975e12a0

【讨论】:

    【解决方案2】:

    因为你做了参考。如果您需要其他行为,则必须进行克隆。 在 lodash 中有 cloneDeep。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-12
      • 2021-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-05
      • 1970-01-01
      相关资源
      最近更新 更多