97

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.

2 Answers 2

168

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);
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Well this is correct answer, but be aware that ElementRef will only work when angular is running in Browser-Thread - where you have direct access to the DOM - and therefore break when you try to run your app in a webworker... Renderer2 is mentioned in the Docs - to being save to use in this cases - but it's marked as experimental and i couldn't find good docs on how to use it yet. Maybe this saves someone the trouble i just had :)
Using 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).
Thanks for pointing that out - any suggestions or links to a Renderer2 Example? My problem is i wanted to 'climb-up' a tree of nested components from a selected one, compare the components constructor-type and set an active-state variable on the intresting ones... i would have liked to do it in a way like with native-element , but know the application will later need the performance gainded from running in a webworker ( also Server-Side-Rendering )... Is my best option to emit an event up the chain, check the parent and store the data in shared-service?
There is not much to it. You inject it and then call one of its methods and pass an ElementRef the method should be applied to alligator.io/angular/using-renderer2 All supported methods are listed in angular.io/api/core/Renderer2
7

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.