问题
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