Angular - 生命周期:要完全加载的子组件

Ask*_*ela 5 lifecycle angular

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

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

@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;
}
Run Code Online (Sandbox Code Playgroud)

有没有办法AppComponent知道是否HelloComponent已满载或者我是否需要内部自定义解决方案HelloComponent

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

您对此主题有何看法?


编辑

到目前为止,我已经尝试了您的建议(挂钩AfterViewInit、利用@ViewChildren...),但没有成功。
为了确定,我在没有这些<ng-container>...<ng-template>东西的情况下再次尝试,只是隐藏了我的HelloComponentusing[hidden]指令......

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

现在,我想利用该<ng-container>...<ng-template>机制的原因是因为我的实际组件比示例重一点点HelloComponent
如果有人有更好的想法继续使用容器模板机制,我洗耳恭听。

Bil*_*ner 1

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