如何更新 child

How to update child

我有一个组件引用了这样的 child 组件

  cc: TheChildComponent;
  @ViewChild('theChildComponent') set details(content: TheChildComponent) {
           this.cc = content;
        };

TheChildComponent 是一个复杂的组件,有几个 dom 元素和一个通过 rest 调用异步更新的数据数组。

每当我检测到 TheChildComponent 中的数据数组发生变化时,我想更新我的变量 this.cc。

虽然我不知道该怎么做,也不知道是否可行。

通常的方法是在子组件更改其状态时在子组件中发出事件。鉴于您无法访问子组件实现,您必须寻找更奇特的解决方案。

我将结合 @ViewChild.

实施 ngDoCheck 生命周期
@ViewChild(TheChildComponent) child: TheChildComponent;

ngDoCheck() {
  if (this.child && this.hasChanged(this.child.array))
    this.cc = this.child.array;
  }
}

private hasChanged(arr: any[]): boolean {
  // check if the child changed its state
}

请记住,此生命周期挂钩会被频繁调用,因此请尽可能精简您的逻辑。

查看 Live demo