2016-08-31 25 views
8

我反覆運行到哪裏,我想訪問一個子組件現有的路由器出口的另一側,而不是一個選擇的情況:你可以使用@ViewChild()或類似的路由器插座?如果是這樣?

Like: 
<router-outlet></router-outlet> 

NOT: 
<selector-name></selector-name> 

這種衝突與ViewChild功能,因爲我知道,但看起來像我的組件應該能夠看到路由器插座內部的內容並與其進行交互,就像在選擇器標籤內部一樣容易。

比如我嘗試這樣做:

export class RequestItemCatsComp { 
    @ViewChild('child') child: RequestItemsComp; 
    ***etc...*** 
ngAfterViewInit() { 
    if (this.child) // Always child is undefined 
     this.groupId = this.child.groupId; 
    } 
} 

但自然,孩子是未定義,因爲這是錯誤的方式。有沒有正確的方法?

我試圖用一個服務來共享數據,但隨後遇到了另一個問題:「這是檢查後表達發生了變化」,這我希望沒有一個黑客補救或啓用PROD模式。

+0

你可以試試'@ViewChild(RequestItemsComp)孩子:RequestItemsComp;'。我不希望它能夠工作(沒有嘗試過),但是@ViewChild('child')'只有在元素有一個模板變量'#child'時纔有效,這對路由組件來說是不可能的。 –

+0

使用服務在路線之間共享數據。你可以使用'setTimeout()'來解決「檢查後表達式已經改變」的錯誤。見https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html#!#afterview –

+0

@Methodician:你檢查了我添加的解決方案嗎?它對你有用嗎? –

回答

20

您可以挖掘到激活事件得到路由器的出口內實例化的組件的參考。

摘自RouterOutlet Docs

路由器出口將發出一個激活事件的新組件 被實例化的任何時間,當它正在 破壞deactivate事件。

例如

@Component({ 
    selector: 'my-app', 
    template: `<h3 class="title">Basic Angular 2</h3> 
    <router-outlet (activate)="onActivate($event)" ></router-outlet> 
    ` 
}) 
export class AppComponent { 
    constructor(){} 

    onActivate(componentRef){ 
    componentRef.sayhello(); 
    } 
} 

@Component({ 
    selector: 'my-app', 
    template: `<h3 class="title">Dashboard</h3> 
    ` 
}) 
export class DashboardComponent { 
    constructor(){} 

    sayhello(){ 
    console.log('hello!!'); 
    } 
} 

這裏是Plunker!!

希望這有助於!

+0

這是一個很好的做法嗎?你將不得不做額外的工作來確定哪個組件已被激活? –

+1

理想情況下,您將使用服務來在組件之間進行交互,並說它取決於您的要求。乾杯!! –

+0

所以這回服務......好的謝謝! –

相關問題