Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 573
Ajeet Eppakayala Avatar asked Aug 17 '19 12:08

Ajeet Eppakayala


People also ask

How to check if element is in focus in Angular?

hasFocus() : whether the document or any element inside the document has focus. document. activeElement : Property containing which element currently has focus.

How do you know if input field has focus?

HTML DOM Document hasFocus() The hasFocus() method returns a true if the document (or any element in the document) has focus. Otherwise it returns false .

What is focus in angular?

The ng-focus directive tells AngularJS what to do when an HTML element gets focus. The ng-focus directive from AngularJS will not override the element's original onfocus event, both will be executed.

What is focus in HTML?

The HTMLElement. focus() method sets focus on the specified element, if it can be focused. The focused element is the element that will receive keyboard and similar events by default.


1 Answers

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.

like image 69
racraman Avatar answered Oct 21 '22 08:10

racraman