1

I want to remove autocomplete time for ngx-mat-datetime-picker

I tried setting in html

<ngx-mat-datetime-picker autocomplete="off">

and created directive with autocimplete="off"

@Directive({
  selector: 'input:not([autocompleteOn])'
})
export class AutocompleteDirective {
  @HostBinding('attr.autocomplete') autoComplete = 'off';
  constructor() {}
}

but it doesn't work and autocomplete still appears enter image description here

1 Answers1

0

Because of the rule below angular cannot select all elements across the dom. That is why input:not([autocompleteOn]) is not working.

Angular only allows directives to apply on CSS selectors that do not cross element boundaries. https://angular.io/api/core/Directive#selector

The librairy here creates a template overlay from this component directive ngx-mat-datetime-picker That's why the underlying input tag doesn't inherit the autocomplete="off" Only adding the attribute on the host tag.

Using JS you could manually add the autocomplete off to all input and form children. As stated in this answer https://stackoverflow.com/a/59301580/4217907 but this would not work since the overlay is created later on when the dialog is opened. So a solution would be this custom directive

@Directive({
  selector: '[autocompleteoff]'
})
export class MatDatetimePickerAutocompleteOffDirective implements OnDestroy{
  openSub;
  constructor(private element: NgxMatDatetimePicker<Date>) {  
    this.openSub = element.openedStream.subscribe((e)=>{
      setTimeout(()=>{
        Array.from(element._popupRef.hostElement.querySelectorAll('input'))
        .forEach(element => {
          element.setAttribute('autocomplete', 'off');
        });
      })
    })
  }
  ngOnDestroy(){
    if(this.openSub) this.openSub.unsubscribe();
  }
}

For some reason the event openedStream triggers too early before the input is rendered making this ugly setTimeout needed for this solution to work.

Worth noting my browser(chrome latest) i did not have autocomplete showing on this example here https://stackblitz.com/edit/angular-zdh58h-dzi5yv?file=src%2Fapp%2Fcard-overview-example.ts

None the less, the objective of having all datepicker inputs set with the attribute autocomplete="off" can be asserted inspecting the dom