首页 文章

从子组件获取父组件的elementRef

提问于
浏览
3

我有 ParentComponentChildComponent . 父组件使用 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 回答

  • 1

    我想到了ATM 2的想法:

    1) Inject the parent component into the child as an optional parameter:

    对于这种情况,父级应该通过公共成员公开elementRef实例 .

    Pros

    • 易于实施

    Contras

    • 孩子与父母的紧密联系:如果现在你有N型父母怎么办?您会在子构造函数中定义N-Optional属性吗?为所有父母使用基类?在这种情况下,您必须在所有N-Parent组件的组件级别使用显式提供程序 .

    2) Share a service instance across parent and child for tracking click events

    在这种情况下,父和子共享服务的公共实例,或多或少看起来像这样:

    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$ stream订阅该流,并在事件上运行逻辑 .

    对于要跨DOM层次结构共享的实例,必须在父组件级别提供ClickTracker类的新实例:

    @Component({
      providers: [ClickTracker]
    })
    export class FooParent{}
    

    层次依赖注入器将负责提供 FooParent 中包含的子组件以及来自父级的 ClickTracker 实例 .

    Pros:

    • 儿童与父母之间没有紧密联系

    Contras:

    • 家长现在负责创建新服务 .
  • -2

    您可以使用输入绑定 .

    对于例如在parent.component.ts中

    public parentRef: ElementRef;
    
    constructor(elementRef:ElementRef) {
      this.parentRef = elementRef;
    }
    

    在child.component.ts中声明一个Input绑定

    @Input public parentRef: ElementRef;
    

    然后在parent.component.html中传递对子组件的引用

    <child-component [parentRef]="parentRef"></child-component>
    

相关问题