javascript – 如何在模板中有ngIf时识别Angular2组件是否已完全加载(包括ViewChilds)

前端之家收集整理的这篇文章主要介绍了javascript – 如何在模板中有ngIf时识别Angular2组件是否已完全加载(包括ViewChilds)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当有条件地加载子项的模板中有ngIf时,是否可以识别Angular2组件(此处为AppComponent)是否已完全加载(包括ViewChilds).

参考:Angular 2 @ViewChild annotation returns 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
    }

}

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

我需要在SlideshowComponent& amp; ControlsComponent已加载并基于此执行操作.

我有一个hacky解决方案,当有多个ViewChilds(不同类型)时不适用
– 使用事件发射器通知子项何时加载.

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

解决方法

PLUNKER

尝试使用ViewChild而不是ViewChild,它提供了Observable的更改,我们可以将其用作钩子.

要跟踪所有ViewChildren,您可以将他们的更改Observables合并为一个并订阅它,然后您获得单一操作点,就像这样

@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');
    });
  }
}
原文链接:https://www.f2er.com/js/157043.html

猜你在找的JavaScript相关文章