【问题标题】:Angular: I am passing ngmodel in a @input from parent to child; change the value of corresponding @input, the value in parent is updatedAngular:我在 @input 中将 ngmodel 从父级传递给子级;改变对应@input的值,更新parent中的值
【发布时间】:2020-04-03 11:37:13
【问题描述】:

Angular:我在 @input 中将 ngmodel 从父级传递给子级;当我更改子项中相应@input 的值时,父项中的值也会更新,导致它的行为类似于 2 路绑定。谁能解释为什么会这样

父 html:

<app-config-form [data]="param"></app-config> //param is ngModel

child.ts:

@Input() data:any = {}

【问题讨论】:

  • HTML 中的} 是什么?
  • 写问题时错字

标签: angular 2-way-object-databinding


【解决方案1】:

您正在使用[(ngModel)]。这意味着您需要两种方式的数据绑定。当您更改与[(ngModel)] 关联的值时,它会在您使用它的所有地方做出反应。 因此,如果您在该变量处不需要 ngmodel,请使用替代方式。

【讨论】:

    【解决方案2】:

    您需要在您的孩子中创建数据副本:

    @Input() data:any = {}
    childData: any;
    
    
    OnInit() {
       this.childData = JSON.parse(JSON.stringify(this.data));
    }
    

    这将让您修改 childData 避免在父组件中更新,因为 childData 是另一个对象而不是数据。在您的示例中,您将对象从父级传递给子级,但实际上是同一个对象,因此,当您在子级中更新它时,它会在父级中更新。

    【讨论】:

      【解决方案3】:

      当输入不是原始类型(数字/字符串/布尔值)时,您所描述的行为就会发生。如果它是一个复杂对象(不同于 null)并且您更改了对象的任何属性,那么该更改将反映在父对象上,因为它是相同的:您处理的是引用,而不是值。

      如果您想避免这种情况,您必须对输入进行深度克隆,如下所示:

      private _data: any;
      @Input() set data(d: any) {
        // If you want to improve performance, use this library to do a deep clone:
        // https://github.com/planttheidea/fast-copy
        // otherwise, you can go with JSON.parse(JSON.sringify(...))
      
        this._data = d ? JSON.parse(JSON.sringify(d)) : null;
      }
      get data(): any {return this._data;}
      

      补充信息

      现在,作为信息:如果您愿意,可以真正使用 2 路数据绑定:

      @Input() data:any = {}
      
      // mandatory: the same name of the @Input, suffixed with "Change"
      @Ouput() dataChange = new EventEmitter<any>();
      

      然后您可以在父级中使用“banana-in-the-box”表示法:

      <app-config-form [(data)]="param"></app-config> //param is ngModel
      

      但更新不会自动触发。每次在child里改,都要调用this.dataChange.emit(value)。

      例如(在孩子身上):

      buttonClickHandler() {
        this.data = 2;
        this.dataChange.emit(2);
      }
      

      【讨论】:

      • 我让他想保持父级中的数据未修改:d
      • 我理解了相反的意思。不过我已经更新了答案。
      【解决方案4】:

      对象是mutable

      Mutable 是一种可以更改的变量。在 JavaScript 中,只有 对象和数组是可变的,而不是原始值。

      这就是价值变化的原因...有一篇关于immutability in js的好文章

      【讨论】:

        猜你喜欢
        • 2020-08-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-17
        • 2020-06-22
        • 2021-12-26
        • 2019-12-04
        • 2018-05-01
        相关资源
        最近更新 更多