Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 783
bucicimaci Avatar asked May 23 '16 06:05

bucicimaci


People also ask

What is host element in Angular?

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.

How do I get ElementRef in Angular 8?

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.

What is element ref?

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.

How can I select an element in a component template?

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.


2 Answers

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);   } } 
like image 147
Günter Zöchbauer Avatar answered Oct 21 '22 23:10

Günter Zöchbauer


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); } 
like image 37
Moslem Shahsavan Avatar answered Oct 22 '22 00:10

Moslem Shahsavan