Angular material date-picker (MatDatepicker) auto completes the date on focus out

3.9k views Asked by At

I am using angular material/mat-datepicker in my project and whenever the user enters one digit inside of it, and goes out of focus - the date picker is auto completing with a random date.

Example

Just enter 1 and go out of focus, or enter 5/5/20

The date picker is adding date automatically

Update: Also I am using reactive forms and I'm validating the input with that approach

Can I disable this ?

1

There are 1 answers

0
Mihira Bandara On

I know this is too late to answer this question. But, I had also faced the same kind of issue with reactive forms and disable the MatDatePicker autocomplete in the following way.

<mat-form-field>
   <input matInput #autocomplete placeholder="Choose a date" formControlName="datePicker">
   <input type="hidden" [matDatepicker]="picker" placeholder="Choose a date" formControlName="datePicker" (dateChange)="autocomplete.value = toFormattedDate($event.value)">
   <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
   <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

Create the following 'toFormattedDate' method in your component.

toFormattedDate(iso: string) {
  const date = new Date(iso);
  console.log(date);
  return `${date.getDate()}/${date.getMonth() + 1}/${date.getFullYear()}`;
}