Search code examples
angularangular-materialdatepicker

Angular Material datepicker incorrect default date


I am using Material datepicker and datepicker's date always default to 1/1/1 with MatNativeDateModule and 1/1/0001 with MatMomentDateModule. Even on setting the date programattically date defaults to 1/1/1.

I am using reactive forms. When I don't provide formControlName, date defaults to current date which is the desired behavior but when I provide formControlName it shows incorrect date.

I am using Angular version 12 with Angular Material version 12.2.5. I am simply importing MatDatepickerModule, MatNativeDateModule and MatMomentDateModule in my main module and in html everything is copied from angular documentation. Below is my code

<mat-form-field appearance="fill">
      <mat-label>Start Date</mat-label>
      <input matInput formControlName="startDate" [matDatepicker]="picker1">
      <mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle>
      <mat-datepicker #picker1></mat-datepicker>
    </mat-form-field>

Solution

  • More code in the question would be nice, but if I understand you correctly..

    Change formControlName="startDate" to [formControl]="startDate" and ensure you have set the formControl in the component.

    E.g:

    startDate = new FormControl(new Date(2021, 1, 1));
    

    If it's part of a FormGroup, formControlName should be used. Then in the .ts,

    yourGroup = new FormGroup({
      startDate = new FormControl(new Date(2021, 1, 1));
    });
    

    More on how to use new Date() here