我有 ParentComponent
和 ChildComponent
. 父组件使用 ng-content
,因此它可以包含任何类型的DOM元素层次结构中的任何内容 .
我的孩子组件有一个特定的要求:
单击子项时,切换其详细信息的显示当子项放在ParentComponent中时,单击父项时,子项应与1中的相同 .
由于父级可以拥有任何内容,因此将 @ContentChild
添加到父级是不合理的,因为...良好的封装 .
所以唯一应该处理的地方是 ChildComponent
. 通过以下方式获取 ParentComponent
非常简单:
// ChildComponent ctor
constructor(@Optional() parent: ParentComponent) { ... }
但是这并没有't help as I need parent component' s ElementRef
所以我可以将click事件处理程序附加到它 .
How can I obtain it the Angular way? †
†我知道我可以获得ChildComponent的ElementRef并向上遍历DOM,寻找最接近的ParentComponent的元素,但这可能比正确的Angular方法做得更多 . 我很确定必须有更好的方法 .
2 回答
我想到了ATM 2的想法:
1) Inject the parent component into the child as an optional parameter:
对于这种情况,父级应该通过公共成员公开elementRef实例 .
Pros :
Contras :
2) Share a service instance across parent and child for tracking click events
在这种情况下,父和子共享服务的公共实例,或多或少看起来像这样:
基本上,父和子都可以通过
click
方法发出新事件 . 他们还可以使用publicclicks$
stream订阅该流,并在事件上运行逻辑 .对于要跨DOM层次结构共享的实例,必须在父组件级别提供ClickTracker类的新实例:
层次依赖注入器将负责提供
FooParent
中包含的子组件以及来自父级的ClickTracker
实例 .Pros:
Contras:
您可以使用输入绑定 .
对于例如在parent.component.ts中
在child.component.ts中声明一个Input绑定
然后在parent.component.html中传递对子组件的引用