如何在模板中存在ngIf时确定Angular2组件是否已完全加载(包括ViewChilds)

tym*_*spy 7 angular-components angular

当有条件地加载子项的模板中有ngIf时,是否可以识别Angular2组件(此处为AppComponent)是否已完全加载(包括ViewChilds).

参考:Angular 2 @ViewChild注释返回undefined 此示例取自上面的引用.感谢kenecaswell

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
    }

}
Run Code Online (Sandbox Code Playgroud)

由于ngIf条件,在加载子组件之前触发ngOnInit && ngAfterViewInit

我需要在加载SlideshowComponent和ControlsComponent时识别并基于此执行操作.

我有一个hacky解决方案,当有多个ViewChild(不同类型)时不适合 - 使用事件发射器通知子加载的时间.

我发布这个问题,因为经过数小时的研究后没有适当的解决方案.

Ank*_*ngh 2

笨蛋

TryViewChildren而不是ViewChild,它提供了一个changesObservable,我们可以将其用作钩子。

要跟踪所有 ViewChildren,您可以将它们的changesObservable 合并为一个并订阅它,然后您将获得单点操作,如下所示

  @ViewChildren(ChildCmp) children: QueryList<ChildCmp>;
  @ViewChildren(AnotherChildCmp) anotherChildren: QueryList<ChildCmp>;

  childrenDetector: Observable<any>; // merged observable to detect changes in both queries

  ngAfterViewInit(){
    this.childrenDetector = Observable.merge(this.children.changes, this.anotherChildren.changes)

    this.childrenDetector.subscribe(() => {

      // here you can even check the count of view children, that you queried
      // eg:  if(this.children.length === 1 && this.anotherChildren.length === 1) { bothInitialized(); }
      // or something like that

      alert('you just initialized a children');
    });
  }
}
Run Code Online (Sandbox Code Playgroud)