Reputation: 51
I want to call a function when the cursor jumps to an input, but only when this happens due to a tab key. That's why I can't use the (focus) event, because that also gets triggered by a click. Is there a way to trigger a function when the cursor jumps into the input by tab key?
Upvotes: -1
Views: 2109
Reputation: 83
If you use the Component Dev Kit (CDK) from Angular Material you can use FocusMonitor to recognize if the element was focused by keyboard, mouse, touch or via code.
Install npm packet:
npm install @angular/cdk --save
Import A11yModule
to your module (for example app.module.ts).
Then add directive cdkMonitorElementFocus to your element. Now you want to use the (cdkFocusChange) event instead of (focus).
.html:
<input cdkMonitorElementFocus (cdkFocusChange)="onFocusChange($event)" value="" />
.ts:
onFocusChange(origin: FocusOrigin): void {
if (origin == null) {
// element blured
} else if (origin == 'keyboard') {
// focused via keyboard
} else if (origin == 'mouse' || origin == 'touch') {
// focused via mouse or touch
} else if (origin == 'program') {
// focused via code
}
}
If you want to monitor a whole subtree of many elements you can use the directive cdkMonitorSubtreeFocus on the parent.
Upvotes: 1
Reputation: 792
It is nearly impossible to handle this scenario using (focus) event alone.
Let me suggest you an alternate way. This may not a 100% valid solution. But this works in my requirement.
Solution:
// Declare one boolean variable and assign it to false.
isClicked = false;
// Create a function to detect mouse down event
onMouseDown() {
this.isClicked = true;
}
// Create a function to detect mouse up event
onMouseDown() {
this.isClicked = false;
}
// Create a function to detect focus event
onFocus() {
if (this.isDown) {
console.log('click event')
} else {
console.log('tab event')
}
}
And here is a sample input box in html with these events.
<input
class="target"
(mousedown)="down()"
(mouseout)="out()"
value=""
(focus)="test($event)"
/>
Upvotes: 0