注入与子组件相同类型的父组件 [英] Inject parent component of the same type as child component

查看:95
本文介绍了注入与子组件相同类型的父组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在角度2中,子组件可以通过构造函数参数注入其父组件。例如:

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!

我猜的原因是Angular 2注入组件本身而不是其父组件。

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

Plunker https://plnkr.co/edit/ddvupV?p=preview

推荐答案

这样工作

constructor(@SkipSelf() @Host() @Optional() parent: TreeNodeComponent) {}

Plunker


  • @SkipSelf()是不会自己注入,请求 TreeNodeComponent

  • @Host()不要看进一步比主机元素

  • @Optional() ??没有父节点 TreeNodeComponent 作为根节点

  • @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

另请参见 http:// blog。 thinkram.io/angular/2015/08/20/host-and-visibility-in-angular-2-dependency-injection.html

这篇关于注入与子组件相同类型的父组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆