Here are two patterns you can use in Angular to tell “tab‐focus” from “click‐focus” on a text input:
1) Use Angular CDK’s FocusMonitor (recommended)
Angular CDK ships with a small utility that already does exactly this for you:
-
Install CDK (if you haven’t already):
npm install @angular/cdk
-
In your module:
import { A11yModule } from '@angular/cdk/a11y';
@NgModule({
imports: [
// …
A11yModule,
],
})
export class AppModule {}
-
In your component:
import { Component, ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { FocusMonitor, FocusOrigin } from '@angular/cdk/a11y';
import { Subscription } from 'rxjs';
@Component({
selector: 'my-input',
template: `
<input #myInput type="text" placeholder="Tab vs Click focus?">
`
})
export class MyInputComponent implements OnInit, OnDestroy {
@ViewChild('myInput', { static: true }) inputRef: ElementRef<HTMLInputElement>;
private fmSub: Subscription;
constructor(private fm: FocusMonitor) {}
ngOnInit() {
// start monitoring
this.fmSub = this.fm
.monitor(this.inputRef.nativeElement, true)
.subscribe((origin: FocusOrigin) => {
// origin === 'keyboard' | 'mouse' | 'touch' | 'program'
console.log('Focus origin:', origin);
if (origin === 'keyboard') {
// user pressed Tab (or similar)
} else if (origin === 'mouse') {
// user clicked
}
});
}
ngOnDestroy() {
this.fmSub.unsubscribe();
this.fm.stopMonitoring(this.inputRef.nativeElement);
}
}
The CDK’s FocusMonitor takes care of edge-cases (touch, programmatic focus, etc.) for you.
2) Roll-your-own with “last key vs last mouse” flags
If you don’t want to pull in CDK, you can watch mousedown & keydown yourself, stash a little flag, and then inspect it on focus:
<input
type="text"
(mousedown)="onMouseDown()"
(keydown.tab)="onTabKeyDown()"
(focusin)="onFocusIn()">
import { Component } from '@angular/core';
@Component({
selector: 'my-input',
templateUrl: './my-input.component.html',
})
export class MyInputComponent {
private lastFocusOrigin: 'mouse' | 'keyboard' = null;
onMouseDown() {
this.lastFocusOrigin = 'mouse';
}
onTabKeyDown() {
this.lastFocusOrigin = 'keyboard';
}
onFocusIn() {
if (this.lastFocusOrigin === 'mouse') {
console.log('Focus via mouse click');
} else if (this.lastFocusOrigin === 'keyboard') {
console.log('Focus via Tab key');
} else {
console.log('Focus by other means');
}
// reset
this.lastFocusOrigin = null;
}
}
Why it works
(mousedown) fires before the element actually receives focus (on click).
(keydown.tab) fires just before focus moves via Tab.
- Finally
(focusin) fires, and you pick up whichever flag was set last.
Both approaches will let you distinguish “did the user tab into this field?” vs. “did they click it?”—pick the one that best fits your app. 😊