How to get host element reference?

TypescriptAngular

Typescript Problem Overview


How can I get the host element reference in Angular 2?

In my case, I want to know if my component has a focus or not.

Typescript Solutions


Solution 1 - Typescript

You get the host element reference using

class MyComponent {
  constructor(private elRef:ElementRef) {
    console.log(this.elRef.nativeElement);
  }
}

You can also subscribe to the focus event

class MyComponent {
  @HostBinding() tabindex = 0;
  @HostListener('focus', ['$event'])
  onFocus(event) {
    console.log(event);
  }
}

Solution 2 - Typescript

Use ViewContainerRef that represents a container where one or more views can be attached to a component.

constructor(private readonly viewRef: ViewContainerRef) {

    console.log(this.viewRef.element.nativeElement);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbucicimaciView Question on Stackoverflow
Solution 1 - TypescriptGünter ZöchbauerView Answer on Stackoverflow
Solution 2 - TypescriptMoslem ShahsavanView Answer on Stackoverflow