我有 ParentComponent
和 ChildComponent
。父组件使用 ng-content
因此它可以在任何类型的 DOM 元素层次结构中包含任何内容。
我的子组件有一个特定的要求:
- When child is clicked it toggles the display of its details
- When child is placed inside
ParentComponent
, then when the parent is clicked, child should do the same as in 1.
由于父级可以有任何内容,因此将 @ContentChild
添加到父级似乎是不合理的,因为......很好的封装。
所以唯一应该处理的地方是 ChildComponent
。通过以下方式访问 ParentComponent
非常简单:
// ChildComponent ctor
constructor(@Optional() parent: ParentComponent) { ... }
但这没有帮助,因为我需要父组件的 ElementRef
,这样我才能将点击事件处理程序附加到它。
如何通过 Angular 方式获取它? †
† I know I could get
ChildComponent
'sElementRef
and traverse the DOM upwards looking for the closestParentComponent
's element, but that's likely more of a hack than the proper Angular way of doing this. I'm pretty sure there must be some better way.
最佳答案
我想到了 ATM 2 的想法:
1)将父组件作为可选参数注入(inject)子组件:
对于这种情况,父级应该通过公共(public)成员公开 elementRef 实例。
优点:
- 易于实现
对比:
- 子级与父级的紧耦合:如果现在您有 N 种父级会怎样?您会在子构造函数中定义 N-Optional 属性吗?为所有 parent 使用一个基类?在这种情况下,您将必须在所有 N 父组件的组件级别使用显式提供程序。
2) 在父子之间共享一个服务实例以跟踪点击事件
在这种情况下, parent 和 child 共享一个公共(public)服务实例,大致如下所示:
export class ClickTracker {
private readonly _clicks$ = new Subject<void>();
readonly clicks$ = this._clicks$.asObservable();
ngOnDestroy(){
this._click$.complete();
}
click(){
this._clicks$.next();
}
}
基本上,父级和子级都可以通过click
方法发出新事件。他们还可以使用公共(public) clicks$
流订阅该流,并对事件运行逻辑。
为了在 DOM 层次结构中共享实例,必须在父组件级别提供 ClickTracker 类的新实例:
@Component({
providers: [ClickTracker]
})
export class FooParent{}
分层依赖注入(inject)器将负责为包含在 FooParent
中的子组件提供来自父组件的 ClickTracker
实例。
优点:
- child 和 parent 之间没有紧密耦合
反面:
- 家长现在负责创建一项新服务。
关于angular - 从子组件获取父组件的 elementRef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48816454/