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
This way it's working
constructor(@SkipSelf() @Host() @Optional() parent: TreeNodeComponent) {}
Plunker
@SkipSelf()
is to not get oneself injected which would apply if TreeNodeComponent
is requested@Host()
don't look further up than the host element@Optional()
?? there is no parent TreeNodeComponent
for the root nodeSee also http://blog.thoughtram.io/angular/2015/08/20/host-and-visibility-in-angular-2-dependency-injection.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With