Skip to content

Instantly share code, notes, and snippets.

@dyazincahya
Created November 12, 2024 13:56
Show Gist options
  • Save dyazincahya/9668ac14acbe9e142924620b53422338 to your computer and use it in GitHub Desktop.
Save dyazincahya/9668ac14acbe9e142924620b53422338 to your computer and use it in GitHub Desktop.
Angular directive to disable browser autofill on input forms (Tested Angular 18)
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');
}
}
@dyazincahya
Copy link
Author

How to Using?

1. Load the Directive first

Example like this:

import { DisableAutofillInputDirective } from './disable-autofill-input.directive';

  @NgModule({
      declarations: [DisableAutofillInputDirective],
      exports: [DisableAutofillInputDirective]
  })
  export class SharedModule { }

2. Add the Directive

Add this DisableAutofillInput on the input form like this:

<input
      formControlName="email"
      DisableAutofillInput
  />

@dyazincahya
Copy link
Author

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