【问题标题】:Angular - Life-cycle: Child component to be fully loadedAngular - 生命周期:要完全加载的子组件
【发布时间】:2019-05-28 13:02:10
【问题描述】:

是否可以通知父组件加载子组件,尤其是在涉及ng-containerng-template 时。
Yes! I see that you've grown strong, my child! p>

假设我们有一个这样的组件:

@Component({
  selector: 'my-app',
  template: `
  <ng-container *ngIf="!showElse; else elseBlock">
    <h1>Hi!</h1>
  </ng-container>
  <ng-template #elseBlock>
    <hello name="{{ name }}"></hello>
  </ng-template>
  <button (click)="showElse = !showElse">Show else</button>
  `,
  styles: ['']
})
export class AppComponent  {
  name = 'Angular';
  showElse = false;
  @ViewChild('hello') hello: HelloComponent;
}

有没有办法让AppComponent 知道HelloComponent 是否已满载,或者我是否需要在HelloComponent 中使用自定义解决方案?

我目前正在使用一个不太理想的解决方案(我不喜欢基于 setTimeout() 的东西)。
以下是我的想法:
- 将EventEmitter 添加到我的HelloComponent
- 使用HelloComponent 的生命周期在ngAfterContentChecked 期间发出事件
- 在我的AppComponent 中拦截此事件并执行此操作。

你对这个话题有什么看法?


编辑

到目前为止,我已经尝试了您的建议(挂钩到 AfterViewInit,使用 @ViewChildren...)但没有成功。
可以肯定的是,我再次尝试不使用 &lt;ng-container&gt;...&lt;ng-template&gt; 的东西,只是使用 [hidden] 指令隐藏我的 HelloComponent...

通过在HelloComponentAfterContentChecked 期间发出一个事件并将这个事件挂钩到AppComponent,它就像一个魅力。 (参见on stackblitz
这个解决方案比我之前基于setTimeout 的解决方案更优雅

现在,我想使用 &lt;ng-container&gt;...&lt;ng-template&gt; 机制的原因是因为我的实际组件只是比示例 HelloComponent一点
如果有人对继续使用容器模板机制有更好的想法,我会全力以赴。

【问题讨论】:

标签: angular lifecycle


【解决方案1】:

就像您建议的那样,在生命周期挂钩 AfterContentChecked() 中使用 EventEmitter 向您的父组件发出事件。它很简单,并且正确使用了 Angular 的生命周期 API。 https://angular.io/guide/lifecycle-hooks#lifecycle-sequence

【讨论】:

    【解决方案2】:

    您可以附加到 AfterViewInit ,但并非总是如此,考虑到您的子组件上有 *ngIf,那么您需要这样做。

    private helloPlaceholder: ElementRef;
    
     @ViewChild('hello') set hello(content: HelloComponent) {
        this.helloPlaceholder = content;
        // you can check and do your stuff here
     }
    

    【讨论】:

      【解决方案3】:

      您可以在您的父组件中使用 ngAfterVIewChecked,它告诉父组件 Angular 已完成对所有子组件的更改检测

      因此,如果您有 5 个子组件,您可以知道所有子视图何时更新,但您无法知道特定子组件是否已更新

      【讨论】:

        猜你喜欢
        • 2017-07-12
        • 1970-01-01
        • 1970-01-01
        • 2017-03-29
        • 2017-01-18
        • 2018-05-02
        • 2020-03-15
        • 2016-07-18
        • 1970-01-01
        相关资源
        最近更新 更多