25

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.

Ajeet Eppakayala
  • 1,186
  • 1
  • 10
  • 17

2 Answers2

30

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.

racraman
  • 4,988
  • 1
  • 16
  • 16
15

At a time you can have one focused input. Probably the easiest way would be to use focus event and pass element to your component

@Component({
  selector: 'my-comp',
  template: `
    <input type="text "(focus)="onFocus($event)" (blur)="onFocus()" />
  `
})
export class AppComponent {
  selectedElement: any;
  onFocus(event) {
    if(event){
       this.selectedElement = event.target;
    } else {
       this.selectedElement = null; 
    }
  }
}

Other option would be to write directive to set specific class on focus

import { Directive, HostListener, HostBinding } from '@angular/core';
@Directive({
  selector: '[trackFocus]'
})
export class TrackFocusDirective {
  @HostBinding('class.my-focused-element') isFocused: boolean;
  constructor() {}

  @HostListener('focus', ['$event']) onFocus(e) {
    this.isFocused = true;
  }
  @HostListener('blur', ['$event']) onblur(e) {
    this.isFocused = false;
  }
}

So now you can do this

<input type="text"  trackFocus/>
Vova Bilyachat
  • 18,765
  • 4
  • 55
  • 80