Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save SackeyDavid/1ec956dea1e0ce330c5d65eb839719dd to your computer and use it in GitHub Desktop.
Save SackeyDavid/1ec956dea1e0ce330c5d65eb839719dd to your computer and use it in GitHub Desktop.
This Angular directive provides a simple way to detect native autofill on an input field and emit an event when the autofill status changes. It uses a debounce mechanism and a promise to asynchronously check for autofill, allowing for a more responsive user experience.
import { Directive, ElementRef, Output, EventEmitter, OnInit } from "@angular/core";
@Directive({
selector: "[nativeAutofill]",
})
export class NativeAutofillDetector implements OnInit {
private elRef: HTMLInputElement;
@Output()
public nativeAutofill: EventEmitter<boolean> = new EventEmitter<boolean>();
constructor(private elementRef: ElementRef) {}
ngOnInit(): void {
this.elRef = this.elementRef.nativeElement;
if (this.elRef) {
this.detectAutofill().then((isAutofilled) => {
this.nativeAutofill.emit(isAutofilled);
});
}
}
private detectAutofill(): Promise<boolean> {
return new Promise<boolean>((resolve) => {
setTimeout(() => {
const isAutofilled =
window.getComputedStyle(this.elRef, null).getPropertyValue("appearance") === "menulist-button";
resolve(isAutofilled);
}, 1200);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment