In Angular 2, a child component can get its parent component injected through a constructor parameter. Example:
@Component({...})
export class ParentComponent {
...
}
@Component({...})
export class ChildComponent {
constructor(private parent: ParentComponent) { }
...
}
This works nice and well as long the parent and child are of different types.
However, another typical use case is a tree structure where each tree node is displayed as a separate component. What should we do if each of the tree node components should have access to its parent? I have tried this:
@Component({...})
export class TreeNodeComponent {
constructor(private parent: TreeNodeComponent) { }
...
}
But this fails with the following runtime exception:
EXCEPTION: Cannot instantiate cyclic dependency!
I guess the reason is that Angular 2 injects the component itself instead of its parent component.
How can I tell angular to inject a component's parent component even though they are of the same type?
Plunker https://plnkr.co/edit/ddvupV?p=preview
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…