9

当模板中有 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(它们的类型不同)时不适合 - 使用事件发射器来通知孩子何时加载。

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

4

2 回答 2

1

柱塞

尝试ViewChildren代替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');
    });
  }
}
于 2016-07-12T10:41:54.317 回答
1

您可以将内容包装在 *ngIf 中,以便在 ngOnInit 完成所有操作之前,html 不会显示任何内容。

<div *ngIf="loaded">
    /* all codes go here */
<div>

OnInit(){
    foo();
    bar(()=>{
        this.loaded = true;
    });
}
于 2017-10-25T15:35:53.057 回答