【发布时间】:2019-05-28 13:02:10
【问题描述】:
是否可以通知父组件加载子组件,尤其是在涉及ng-container 和ng-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...)但没有成功。
可以肯定的是,我再次尝试不使用 <ng-container>...<ng-template> 的东西,只是使用 [hidden] 指令隐藏我的 HelloComponent...
通过在HelloComponent 的AfterContentChecked 期间发出一个事件并将这个事件挂钩到AppComponent,它就像一个魅力。 (参见on stackblitz)
这个解决方案比我之前基于setTimeout 的解决方案更优雅
现在,我想使用 <ng-container>...<ng-template> 机制的原因是因为我的实际组件只是比示例 HelloComponent 重一点。
如果有人对继续使用容器模板机制有更好的想法,我会全力以赴。
【问题讨论】:
-
我认为使用 ViewChildren 可以订阅“queryList”的更改,angular.io/api/core/ViewChildren。
-
检查this answer 我不知道为什么被否决