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

隐身守侯 提交于 2020-04-18 07:19:08

问题


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.


回答1:


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.




回答2:


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/>


来源:https://stackoverflow.com/questions/57536298/how-to-check-if-an-input-field-is-in-focus-in-angular-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!