2017-07-03 64 views
2

我有一個佈局組件,其中有一個<router-outlet>,其中子組件由路由器動態插入。如何知道子元素何時在Angular中完成渲染?

我怎麼知道,當插入子元素,並建設完成它的看法?

而且,我不能手動火從子組件的事件,因爲我想這個解決方案是通用的。

+0

你檢查了ngafterviewinit裏面的子組件 – Sreemat

+0

你是什麼意思的「檢查」?我如何知道它是否是從父組件調用的? –

+0

'<路由器出口(激活)= 「onActivated($事件)」>' – yurzui

回答

2

您可以綁定到使用@ViewChild綁定<router-outlet>組件。

對於使用<router-outlet>添加此的任何組件:

/** 
* Gain access to the inner route child. 
*/ 
@ViewChild(RouterOutlet) 
public outlet: RouterOutlet; 

然後,您可以收聽這樣的變化:

public ngAfterViewInit(): void { 
    this.outlet.activateEvents.subscribe((component) => { 
     // gets passed the new child component instance 
    }); 
    this.outlet.deactivateEvents.subscribe(() => { 
     // the child component has been destroyed 
    }); 
    if (this.outlet.isActivated) { 
     // will be false if there is no child route active 
    } 
} 
+0

謝謝!我已經解決了這個問題。它對我的用例非常有用。我最好使用'@ ViewChild',而不是使用'(activate)'綁定。 –

+1

@SlavaFominII https://www.bennadel.com/blog/3038-eventemitter-is-an-rxjs-observable-stream-in-angular-2-beta-6.htm#comments_47949 – yurzui

3

路由器呼籲router-outletactivateWith方法,它創建了一個componentRef,重視它到了router-outlet容器。然後它發出activate事件:

this.activateEvents.emit(this.activated.instance); 

此時被創建並附加到DOM該組件的視圖。然而只有附件的constructor被執行。沒有生命週期掛鉤。在下次更改檢測期間,將調用附加組件的生命週期掛鉤。

您可以通過(activate)輸出訂閱此事件作爲yurzui表明:

<router-outlet (activate)="onActivated($event)"></router-outlet> 

或使用事件發射器,這是不建議:

this.outlet.activateEvents.subscribe((component) => { 
     this.activated = true; 
}); 

所以,如果,例如,你想知道什麼時候ngOnInit被稱爲子組件,你可以這樣做:

const activated = false; 

onActivated() { 
    this.activated = true; 
}); 

ngAfterViewInit() { 
    if (this.activated) { 
    // lifecycle hooks for the child component have been called 
    } 
} 
+0

謝謝!我認爲這是一個合理的解決方案。但是,我決定使用'@ ViewChild'方法,因爲它可以將單個函數內部的功能隔離開來,而無需向模板添加額外的代碼。 –

+0

@SlavaFominII,如果你只是使用ThinkingMedia的方法,那麼生命週期鉤子就不會在'activateEvents.subscribe(()=> {//傳遞新的子組件實例''。它實際上並沒有多大關係如何訂閱激活的情況下,最重要的是這種邏輯'ngAfterViewInit(){ 如果(this.activated){'。我覺得角不鼓勵訂閱的事件發射器直接 –

+0

其實,我正在使用這個解決方案,基於ThinkingMedia的回答,它的效果很好:https://gist.github.com/slavafomin/dc53ae995a449e13807217ae0b582c27 –

相關問題