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.
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);
}
}
ElementRef is not the problem. The problem is using its nativeElement property. The Angular team had a strong opinion against using ElementRef.nativeElement in pre-release times, but softened their stance after release because so many were just not interested in WebWorker and Server-Side-Rendering. The main limitation of Renderer2 is that it only allows to set properties of an element, but no way to read from it (otherwise it wouldn't work with SSR and WW).ElementRef the method should be applied to alligator.io/angular/using-renderer2 All supported methods are listed in angular.io/api/core/Renderer2Use 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);
}