Created
January 25, 2024 13:54
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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