在Angular 2中,子組件可以通過構造函數參數注入其父組件。例如:注入與子組件類型相同的父組件
@Component({...})
export class ParentComponent {
...
}
@Component({...})
export class ChildComponent {
constructor(private parent: ParentComponent) { }
...
}
這個效果很好,只要父母和孩子是不同的類型。
但是,另一個典型的用例是樹結構,其中每個樹節點顯示爲一個單獨的組件。如果每個樹節點組件都可以訪問其父項,我們應該怎麼做?我曾經嘗試這樣做:
@Component({...})
export class TreeNodeComponent {
constructor(private parent: TreeNodeComponent) { }
...
}
但這種失敗,出現以下運行時異常:
EXCEPTION: Cannot instantiate cyclic dependency!
我猜原因是角2注入部件本身,而不是它的父組件。
我怎麼能告訴角注入組件的父組件,即使它們是相同類型?
Plunkerhttps://plnkr.co/edit/ddvupV?p=preview
爲什麼要注入父項,爲什麼不直接使用數據綁定? –
試試這個:http://stackoverflow.com/questions/34540615/how-do-i-inject-a-parent-component-into-a-child-component – Damitha