强制 Angular 子组件完全渲染

Force Angular child component to render completely

我有以下 Stackblitz.

当我更新子数据源时它没有完全呈现,下面的方法没有被调用,

 updatedSelectedText() {
    this.SelectedData = "";
    console.log(this.data);
    this.data.forEach(el => {
      if (el.Selected) this.SelectedData += el.Text;
    });
  }

我可以让它调用

ngDoCheck() {
    // this.updatedSelectedText();
  }

但在实际项目中,我写了很多复杂的逻辑,我不想调用 ngDoCheck 方法。

有没有办法强制子组件完全渲染

我尝试了ChangeDetectionStrategy,但这不起作用。

为什么不将 "child2" 传递给 onEmitEvent 并调用函数 updatedSelectedText()?

也就是说,你改变你的 app.component.html

<!--see that use a template reference variable "#child2", and pass as
    argument to update function -->
<app-child1 (onEmit)="update($event,child2)" [data]="jsondata"></app-child1>
<app-child2 #child2 [data]="jsondata.AdDimensionsMaster"></app-child2>

在app.component.ts的更新函数中直接调用函数

//get the "child2" as "any"
update(event: any,child2:any) {
    this.jsondata.AdDimensionsMaster[event].Selected = true;
    this.jsondata.isactive = true;
    child2.updatedSelectedText() //<--call the function
}
  1. 在 Child2Component 中,updatedSelectedText 方法在 ngOnInit 中调用,该方法只调用一次 - 当组件初始化时。有两种方法可以解决:
    • 通过对 @Input()
    • 使用 setter/getter
    • 通过使用 NgOnChanges 生命周期钩子

注意:setter 和 ngOnChanges 都在 ngOnInit 之前被调用,所以你可以避免这个 hook

  1. 在 AppComponent 中,update 方法应该更新 jsondata 对象而不是更改单个 属性

看看Stackblitz