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.
To turn an Angular component into something rendered in the DOM you have to associate an Angular component with a DOM element. We call such elements host elements. A component can interact with its host DOM element in the following ways: It can listen to its events.
Getting ElementRef in Component ClassCreate a template reference variable for the element in the component/directive. Use the template variable to inject the element into component class using the ViewChild or ViewChildren.
Angular ElementRef is a wrapper around a native element inside of a View. It's simply a class that wraps native DOM elements in the browser and allows you to work with the DOM by providing the nativeElement object which exposes all the methods and properties of the native elements.
Add a template reference variable to the component HTML element. Import @ViewChild decorator from @angular/core in component ts file. Use ViewChild decorator to access template reference variable inside the component.
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); } }
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With