问题描述
在角度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
-
@SkipSelf()
是不会自己注入,请求TreeNodeComponent
-
@Host()
不要看进一步比主机元素 -
@Optional()
??没有父节点TreeNodeComponent
作为根节点
@SkipSelf()
is to not get oneself injected which would apply ifTreeNodeComponent
is requested@Host()
don't look further up than the host element@Optional()
?? there is no parentTreeNodeComponent
for the root node
另请参见
这篇关于注入与子组件相同类型的父组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!