Search code examples
angularelementref

Get ElementRef from component instance


On my Angular library I have a code similar as below:

test.component.html:

<third-party-component #tpComponent></third-party-component>
<my-component [tp-component]="tpComponent"></my-component>

my-component.component.ts:

import { Component, Input, OnInit } from '@angular/core';
import { ThirdPartyComponent } from '@3rd/party-library';

@Component({
  selector: 'my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css']
})
export class MyComponent implements OnInit {
  @Input('tp-component') tpComponent: ThirdPartyComponent;

  ngOnInit() {
    this.tpComponent.doSomething();
  }
}

I am looking for a way, if there is any, to access the ElementRef from the ThirdParyComponent instance passed as the @Input property - unfortunately I can't change the ThirdParyComponent to expose its own ElementRef.

PS: I know I can create a method on MyComponent to set both the ThirdParyComponent instance and its ElementRef, but I would like to simplify this with the @Input.

Is there any way to achieve this?


Solution

  • In the component housing both third-party-component and my-component, can you do:

    @ViewChild('tpComponent') tpComponentElementRef: ElementRef;
    ....
    <my-component [tp-component]="tpComponent" 
                  [tp-component-elementRef]="tpComponentElementRef"></my-component>
    ....
    @Input('tp-component') tpComponent: ThirdPartyComponent;
    @Input('tp-component-elementRef') tpComponentElementRef: ElementRef;
    

    Something like this?