2016-07-12 6 views
7

조건부로 템플릿에 ngIf가있을 때 Angular2 구성 요소 (여기서는 AppComponent)가 완전히로드되는지 (ViewChilds 포함) 식별 할 수 있습니까? 자식을로드합니다.템플릿에 ngIf가있을 때 Angular2 구성 요소가 완전히로드되었는지 (ViewChilds 포함) 식별하는 방법

참조 : Angular 2 @ViewChild annotation returns undefined 이 예제는 위 참조에서 가져온 것입니다. ngOnInit & & ngAfterViewInit이 아이 컴퍼넌트 전에 해고 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 
    } 

} 

덕분에 때문에 ngIf 조건 나는 SlideshowComponent & ControlsComponent이로드 될 때 식별하고 그 기반으로 작업을 수행 할 필요가

의로드됩니다.

다른 ViewChild가있을 때 적합하지 않은 해킹 해결책이 있습니다. (다른 유형 임) - 이벤트 이미 터를 사용하여 하위로드 시점을 알립니다.

몇 시간의 연구 끝에 적절한 해결책이 없기 때문에이 질문을 게시하고 있습니다.

답변

1

PLUNKER

관찰 가능한 changes 제공하는 대신 ViewChildViewChildren을 시도, 우리는 후크로 사용할 수 있습니다.

는, 당신은 당신이 HTML 있도록 * ngIf에 물건을 포장 수있는이

@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'); 
    }); 
    } 
} 
+0

안녕하세요, 제 문제는 3 가지 구성 요소 (ViewChild)가 서로 다른 유형이고 3 가지 구성 요소 (ViewChild)가 모두로드되고 작업을 수행 할 때를 식별하고 싶습니다. 나는 그 질문을 갱신했다. 감사합니다. – tymspy

+0

내가 무엇을 할 수 있는지 보도록하겠습니다. –

+1

OK, 문제는'* ngIf'에 의해 자식 구성 요소가 ViewInit에서 초기화되지 않도록하기 때문에, 이제는 ViewChildren이 더 의미가 있습니다. 그것은 아이들이 초기화 할 때 당신에게 말할 수 있습니다. [이 PLUNKER] (http://plnkr.co/edit/HevkaqUyqmkAnvgPwm7v?p=preview) –

1

처럼 행동 한 점을 얻을 하나에 자신의 changes Observables은 병합 할 수 있습니다, 모든 ViewChildren을 추적하고 구독하려면 ngOnInit이 모두 끝날 때까지 아무 것도 표시하지 않습니다.

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

OnInit(){ 
    foo(); 
    bar(()=>{ 
     this.loaded = true; 
    }); 
}