2016-11-16 120 views
0

我正在使用Angular2路由器實現主 - 細節屏幕。 我有一個組件在其模板中定義了資源列表(ul/li格式):主控部分。列表中的每個資源都可以通過「routerLink」綁定進行點擊。在Angular2中使用路由器(路由器插座)實現「主 - 細節」

在相同的模板中,我定義了一個路由器插座。這個想法是:當我點擊列表中的一個資源(ul/li)時,Angular2應該在路由器插座的位置顯示/呈現可編輯的表單。我可以更改數據並按保存按鈕。 (詳細信息部分)

當更新(保存)此資源時,我想要更新資源列表(ul/li),因爲可能某些數據已更改,這也會顯示在資源列表中(例如作爲資源顯示名稱)。

由於Angular2正在管理細節組件,我沒有在我的html模板中聲明組件。但是,因爲我沒有聲明細節組件,所以我沒有對事件作出反應的鉤子(如更改事件)。也就是說,當我的表單成功更改後,我會發出「更改事件」。基於這樣一個事件,我可以在'主部分'實現一個處理程序,這樣主人可以通過刷新資源列表(ul/li)來更新自己。

問題是:由於在我的應用程序中引入了Angular2路由器功能,因此我已經失去了主從組件之間的關係。

問題:有沒有解決這種模式的方法?

+0

請添加一些代碼來幫助。 –

+0

嗨馬杜,我會重新說明我上面更簡潔地描述的問題;-) – user2120188

+0

嗨馬杜,我將重新說明我上面更簡潔地描述的問題;-)是否有可能是呈現「在」路由器插座組件通知(父)組件它已更改? |通常你會發出一個事件,父母可以對此作出反應。在這種情況下,路由器插座是需要渲染的組件(在路由配置中聲明)的「佔位符」。由於組件本身(在html模板中)不存在,因此我無法聲明父級或其他人可以對其作出反應的任何事件綁定。 – user2120188

回答

2

理想的方法是使用,Component communication via a service

,你也可以在下面嘗試,

import { Component , Output, EventEmitter} from '@angular/core'; 

@Component({ 
    selector: 'my-app', 
    template: `Angular Route 
    <hr /> 
    <a routerLink="/child1" >Child 1</a> 
    <a routerLink="/child2" >Child 2</a> 
    <hr /> 
    Inside Parent component 
    <br /> 
    <br /> 
    Subscription from child : {{result | json}} 
    <hr /> 
    <div> Child Component</div> 
    <br /> 
    <router-outlet 
    (activate)='onActivate($event)' 
    (deactivate)='onDeactivate($event)'></router-outlet> 
    ` 
}) 
export class AppComponent { 
    result: any = {}; 

    constructor(){ 
    } 

    childSubscription: any; 

    onActivate($event){ 
    if(!!$event['parentNotifier']){ 
     this.childSubscription = $event['parentNotifier'].subscribe(res => { 
      this.result = res; 
     }); 
    } 
    } 

    onDeactivate($event){ 
    if(!!this.childSubscription){ 
     this.childSubscription.unsubscribe(); 
    } 
    } 
} 

@Component({ 
    selector: 'my-app', 
    template: `I am a child 
    <button (click)='clickMe()' >Click me to notify parent</button> 
    ` 
}) 
export class ChildComponent1 { 
    @Output() parentNotifier:EventEmitter<any> = new EventEmitter<any>(); 

    clickMe(){ 
    this.parentNotifier.next('I am coming from child 1!!'); 
    } 
} 

@Component({ 
    selector: 'my-app', 
    template: `I am a child 
    <button (click)='clickMe()' >Click me to notify parent</button> 
    ` 
}) 
export class ChildComponent2 { 
    @Output() parentNotifier:EventEmitter<any> = new EventEmitter<any>(); 

    clickMe(){ 
    this.parentNotifier.next('I am coming from child 2!!'); 
    } 
} 

但是請注意,需要由家長樣品中莫名其妙地稱爲像上面我已經使用了事件的名稱它直接parentNotifier

這是Plunker !!

希望這有助於!

+0

謝謝,馬杜。順便說一句,我通過服務檢查並嘗試了你以前的建議。關於第二個想法,我喜歡這種方法,因爲Redux只有一步之遙,那就是如果我遵循這種方法,我在概念上使用Redux進行對齊。所以也值得嘗試一下服務方法。感謝您的見解! – user2120188

+0

@ user2120188:很酷,我已經更新了答案,您可以接受它。 –

相關問題