Created
November 12, 2024 13:56
-
-
Save dyazincahya/9668ac14acbe9e142924620b53422338 to your computer and use it in GitHub Desktop.
Angular directive to disable browser autofill on input forms (Tested Angular 18)
This file contains 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, | |
Renderer2, | |
ElementRef, | |
HostListener, | |
AfterViewInit, | |
} from '@angular/core'; | |
@Directive({ | |
selector: '[DisableAutofillInput]', | |
}) | |
export class DisableAutofillInputDirective implements AfterViewInit { | |
constructor( | |
private el: ElementRef, | |
private renderer: Renderer2, | |
) {} | |
ngAfterViewInit(): void { | |
// Set readonly secara default saat direktif diinisialisasi | |
this.renderer.setAttribute(this.el.nativeElement, 'readonly', 'true'); | |
} | |
// Event listener saat elemen menerima focus | |
@HostListener('focus') | |
onFocus(): void { | |
this.renderer.removeAttribute(this.el.nativeElement, 'readonly'); | |
} | |
// Event listener saat elemen kehilangan focus | |
@HostListener('blur') | |
onBlur(): void { | |
this.renderer.setAttribute(this.el.nativeElement, 'readonly', 'true'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Follow the Article https://www.kang-cahya.com/2024/11/tips-angular-cara-mengatasi-autofill.html