当模板中有 ngIf 有条件地加载子组件时,是否可以识别 Angular2 组件(此处为 AppComponent)是否已完全加载(包括 ViewChilds )。
参考:Angular 2 @ViewChild 注解返回 undefined 这个例子取自上面的参考。感谢肯尼卡斯韦尔
import {Component, ViewChild, OnInit, AfterViewInit} from 'angular2/core';
import {ControlsComponent} from './child-component-1';
import {SlideshowComponent} from './slideshow/slideshow.component';
@Component({
selector: 'app',
template: `
<div *ngIf="controlsOn">
<controls ></controls>
<slideshow></slideshow>
</div>
`,
directives: [SlideshowComponent, ControlsComponent]
})
export class AppComponent {
@ViewChild(ControlsComponent) controls:ControlsComponent;
@ViewChild(SlideshowComponent) slide:SlideshowComponent;
controlsOn:boolean = false;
ngOnInit() {
console.log('on init', this.controls);
// this returns undefined
}
ngAfterViewInit() {
console.log('on after view init', this.controls);
// this returns null
}
}
由于 ngIf 条件,在加载子组件之前会触发 ngOnInit && ngAfterViewInit
我需要确定 SlideshowComponent 和 ControlsComponent 何时加载并基于此执行操作。
我有一个 hacky 解决方案,当有多个 ViewChilds(它们的类型不同)时不适合 - 使用事件发射器来通知孩子何时加载。
我发布这个问题是因为经过数小时的研究没有适当的解决方案。