2016-09-21 63 views
0

調用根組件的方法,我在我的應用程序幾個組件:角2:嵌套的子組件

//.ts: 

RootComponent 
-ParentComponent 
--ChildComponent 
---LastLevelComponent 


//.html 

<root-component> 
<parent-component> 
    <child-component> 
    <last-level-component></last-level-component> 
    </child-component> 
</parent-component> 
</root-component> 

我想打電話給Rootcomponent從LastLevelComponent的方法。

我知道EventEmitter,但問題是我需要將 值傳遞給每個子組件。 有沒有什麼辦法可以直接調用 從LastLevelComponent RootComponent的方法,而不是 依賴於ParentComponent或ChildComponent。

回答

0

您可以在您的LastLevelComponent中使用@Input()。 或者沒有Child-和ParentComponent的@Output()需要使用此事件。

//.html 

<root-component #rootCmp> 
<parent-component> 
    <child-component> 
    <last-level-component [root-comp]="rootCmp" (myOutput)"rootCmp.func()"></last-level-component> 
    </child-component> 
</parent-component> 
</root-component> 
0

您可以通過創建服務來解決此問題。遵循以下步驟:

  1. 創建服務

@Injectable() 出口類CompService {

private componentRef = null; 

constructor(){ 
} 

getParent(){ 
    return this.componentRef; 
} 

setParent(ref){ 
    this.componentRef = ref; 
} 

}

  • 包括此服務位於您的根組件的供應商部分中:
  • @Component({ 。 。 。

    providers: [CompService] 
    

    }) 出口類RootComponent {

    constructor(
        private cmpService?: CompService) 
    { 
    } 
    

    }

  • 在根組件的初始化,呼叫設置組件服務值指向根:

    ngOnInit(){ this.cmpService.setParent(this); }

  • 在子組件或最後一級組件,調用此服務來檢索根組件:

  • @Component(。{ }) 出口類LastLevelComponent {

    constructor(
        private cmpService?: CompService) 
    { 
    } 
    
    someMethod(){ 
        if (this.cmpService){ 
         let parentCtrl = this.cmpService.getParent(); 
    
         // Call your parent method or property here 
         // if (parentCtrl) 
         // parentCtrl.rootMethod(); 
        } 
    } 
    

    }

    您可能會注意到CompSer副本是只有設置在根組件的提供者部分。這使得有一個這種服務的實例。因此,所有子組件都將繼承指向根組件的服務設置。

    您只需調用每個子組件中服務的getParent方法即可訪問根組件公共方法,屬性和事件。

    此外,該服務是可重用的,並避免任何其他組件的依賴。