Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject parent component of the same type as child component

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

like image 562
user928437 Avatar asked Feb 29 '16 19:02

user928437


1 Answers

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 node

See also http://blog.thoughtram.io/angular/2015/08/20/host-and-visibility-in-angular-2-dependency-injection.html

like image 135
Günter Zöchbauer Avatar answered Oct 11 '22 12:10

Günter Zöchbauer