gpt4 book ai didi

Angular - 生命周期 : Child component to be fully loaded

转载 作者:太空狗 更新时间:2023-10-29 17:58:04 24 4
gpt4 key购买 nike

是否可以通知父组件加载子组件,尤其是当涉及到 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;
}

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

我目前正面临一个不太理想的解决方案(我不喜欢基于 setTimeout() 的东西)。
以下是我的想法:
- 添加 EventEmitter到我的HelloComponent ;
- 使用 HelloComponent的生命周期中发出一个事件,比方说,ngAfterContentChecked
- 在我的 AppComponent 中拦截此事件然后去做。

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


编辑

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

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

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

最佳答案

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

关于Angular - 生命周期 : Child component to be fully loaded,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56342917/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com