Skip to content

Instantly share code, notes, and snippets.

@AlejandroPerezMartin
Last active April 11, 2023 15:18
Show Gist options
  • Save AlejandroPerezMartin/ecd014cb8104c235b582f3a3e1649cf7 to your computer and use it in GitHub Desktop.
Save AlejandroPerezMartin/ecd014cb8104c235b582f3a3e1649cf7 to your computer and use it in GitHub Desktop.
Angular 9+ Directive to remove focus after clicking the specified selector/s
import { Directive, HostListener, ElementRef } from '@angular/core';
/**
* This directive removes focus from the selectors after clicking on them
*/
@Directive({
selector: 'button, a' // your selectors here!
})
export class FocusRemover {
constructor(private elRef: ElementRef) {}
@HostListener('click') onClick() {
this.elRef.nativeElement.blur();
}
}
@Tamal2017
Copy link

ok thanks

@ElenaG518
Copy link

very nice!

@mrtabaa
Copy link

mrtabaa commented Mar 13, 2022

In my case, it has to be wrapped with setTimout() like this otherwise the timing messes up with it to function properly:

@HostListener('click')
onClick() {
setTimeout(() => this.elRef.nativeElement.blur());
}

@m4n50n
Copy link

m4n50n commented Apr 11, 2023

Thanks👌

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment