Detect Input Focus Using Angular 2+
You could also use FocusMonitor from @angular/cdk.
https://material.angular.io/guide/creating-a-custom-form-field-control#focused
focused = false;
constructor(fb: FormBuilder, private fm: FocusMonitor, private elRef: ElementRef<HTMLElement>) {
...
fm.monitor(elRef.nativeElement, true).subscribe(origin => {
this.focused = !!origin;
this.stateChanges.next();
});
}
ngOnDestroy() {
...
this.fm.stopMonitoring(this.elRef.nativeElement);
}
There are focus
and blur
events:
<input (blur)="onBlur()" (focus)="onFocus()">
For those using @angular/material
, you can get a reference to the MatInput
instance which implements MatFormFieldControl
interface exposing a nice focused
property.
<mat-form-field>
<input matInput #searchInput="matInput" type="text" />
<mat-icon matPrefix svgIcon="filter" [color]="searchInput.focused ? 'primary' : ''"></mat-icon>
</mat-form-field>