How to get host element reference?
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.
Solution 1:
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:
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);
}