Skip to content

Instantly share code, notes, and snippets.

@kerren
Last active March 23, 2024 09:12
Show Gist options
  • Save kerren/71c67335d328ae4796f8d1a6e7b3277d to your computer and use it in GitHub Desktop.
Save kerren/71c67335d328ae4796f8d1a6e7b3277d to your computer and use it in GitHub Desktop.
A directive that allows you to see if an input is in focus or not. See my blog article here https://blog.entrostat.com/angular-inputs-improved-error-ux/ and see StackOverflow article that inspired this here https://stackoverflow.com/questions/57536298/how-to-check-if-an-input-field-is-in-focus-in-angular-7/57536348#57536348
import { Directive, HostListener, signal } from '@angular/core';
@Directive({
selector: '[appTrackFocus]',
standalone: true,
exportAs: 'isFocused',
})
export class TrackFocusDirective {
isFocused = signal(false);
@HostListener('focus', ['$event']) onFocus() {
this.isFocused.set(true);
}
@HostListener('blur', ['$event']) onblur() {
this.isFocused.set(false);
}
}
@kerren
Copy link
Author

kerren commented Mar 23, 2024

Check out https://blog.entrostat.com/angular-inputs-improved-error-ux/ to see how to bind to this in your inputs and change their styles based on the isFocused signal.

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