0

I want to access the ElementRef of an ancestor component
(which is not controlled by me; means I cannot simply expose the desired object on it).

So basically I could inject the Component itself and then use the functionality of the render3#getHostElement function (returns the ElementRef of a given Component Instance but unfortunately it is not exported from the @angular/core package).

<mat-form-field>                  <!-- the elRef of this one; but is potentially not a direct ancestor -->
  <div>                           <!-- potentially some other elements in between -->
    <my-component></my-component>
  </div>
</mat-form-field>
@Component({...})
class MyComponent {
  constructor(formField: MatFormField) {
   const elRefOfFormField = getHostElement(formField) // basically what I need
  }
}

So is there a 'clean' way to receive this HostElement?

  • imho it should be sth analogous to how I can access a children ElementRef of a component @ViewChild(MatFormField, {read: ElementRef})

It's not an option to do something like elementRef.nativeElement.closest('mat-form-field') (sometimes there are multiple options how to use a component/directive).

  • you can use a service, set the value there and then you can use it across the angular application. Just make sure the service is injected in the AppModule – Manish Mar 16 '22 at 07:03
  • @Manish it would then be better to just provide it through an `@Input()`. But the goal is to have the solution self-contained and generic. – mumenthalers Mar 16 '22 at 08:51
  • Does this answer your question? [How to get the parent DOM element reference of an angular2 component](https://stackoverflow.com/questions/41273384/how-to-get-the-parent-dom-element-reference-of-an-angular2-component) – jhyot Mar 16 '22 at 11:10
  • @jhyot - the other component is potentially not a direct parent in the DOM - therefore no. – mumenthalers Mar 17 '22 at 10:52

0 Answers0