How to check if an input field is in focus in Angular 7

Ajeet Eppakayala picture Ajeet Eppakayala · Aug 17, 2019 · Viewed 10.7k times · Source

I have a form and I want to know if any of the input fields in the form are focused or not?

I read the 'NgForm' documentation but didn't find anything related to 'focus'.

I found touched but it doesn't satisfy needs.

Answer

racraman picture racraman · Aug 17, 2019

You can use the focus and blur events, to track as fields gain or lose focus :

<input (focus)="onFocus()" (blur)="onBlur()">

There are also javascript’s own :

document.hasFocus() : whether the document or any element inside the document has focus.

document.activeElement : Property containing which element currently has focus.