htmlformsautocompleteautofillangular-input

Angular mat-form-filed input disable autocomplete


I am using angular material for all my controls. We have a requirement to disable auto-complete so that any previously typed value will not show up. I have my code as below. I tried autocomplete "off" "disabled" and other suggestions that I found online. But nothing seems to work.

<mat-form-field
  [ngClass]="{ 'invalid-uinque-id': (form.errors.locatorId || form.errors.locatorIdInvalidBadge) }"
  id="sta_BadgeFormField"
>
  <input
    formControlName="locatorId"
    (blur)="onBlurLocatorVendorMethod(selectedVendor.id)"
    matInput
    i18n-placeholder="Locator Badge ID|Placeholder for locator badge id label in add staff dialog@@addstaffLocatorBadgeId"
    placeholder="Locator Badge ID"
    name="locatorId"
    maxlength="20"
    [errorStateMatcher]="esMatcher"
    autocomplete="disabled"
  /> 
</mat-form-field>

Solution

  • In the past, many developers would add autocomplete="off" to their form fields to prevent the browser from performing any kind of autocomplete functionality. While Chrome will still respect this tag for autocomplete data, it will not respect it for autofill data.

    One workaround is to put an unknown value in the autocomplete,

    <input type="text" name="somethingAutofillDoesntKnow" autocomplete="doNotAutoComplete" />.

    When testing this it worked for me most of the time, but for some reason didn't work anymore afterwards.

    My advise is not to fight against it and use it's potential by properly using the autocomplete attribute as explained here.

    <fieldset>
       <legend>Ship the blue gift to...</legend>
       <p> <label> Address:     <textarea name=ba autocomplete="section-blue shipping street-address"></textarea> </label>
       <p> <label> City:        <input name=bc autocomplete="section-blue shipping address-level2"> </label>
       <p> <label> Postal Code: <input name=bp autocomplete="section-blue shipping postal-code"> </label>
    </fieldset>
    

    BUT (Directive)

    If you still want to keep focusing on disabling part, here is the closest solution for you to achieve this with directive.

    import { Directive, HostBinding, Attribute } from '@angular/core';
    
    @Directive({
        selector: '[matInput]',
    })
    export class AutocompleteOffDirective {
    
        @HostBinding('attr.autocomplete') auto;
        constructor(@Attribute('autocomplete') autocomplete: string) {
            this.auto = autocomplete || 'off'
        }
    
    }