Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
656 views
in Technique[技术] by (71.8m points)

dependency injection - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...