Angular Material Datepicker – manual date entry in the input field

Issue

Datepicker works fine until I type the date manually in. If I type a date between 01.MM.YYYY and 12.MM.YYYY the value switches to MM.DD.YYYY but if I type for example 16.09.2021 it stays DD.MM.YYYY.

How can I change the date format from input field?

HTML

<div class="form-group inline datepicker">
  <mat-form-field appearance="fill">
      <input matInput
             [matDatepicker]="validFromPicker"
             [formControl]="validFromFormControl"
             (dateChange)="setValidFromDate($event.value)">
      <mat-datepicker-toggle matSuffix [for]="validFromPicker"></mat-datepicker-toggle>
      <mat-datepicker #validFromPicker></mat-datepicker>
  </mat-form-field>
</div>

TypeScript

 validFrom: Date;
 validFromFormControl: FormControl;
 
 ngOnInit() {
   this.validFromFormControl = new FormControl(new Date());
   this.validFrom = new Date();
 }

 setValidFromDate($event: any) {
   this.validFrom = $event;
 }

I tried to set in AppModule the locale like in this thread – https://stackoverflow.com/a/54670289/11945378 but without success.

Solution

You need to use MomentDateAdapter with which you can easily change the locale:

providers: [
// The locale would typically be provided on the root module of your application. We do it at
// the component level here, due to limitations of our example generation script.
{ provide: MAT_DATE_LOCALE, useValue: 'en-US' },

// `MomentDateAdapter` and `MAT_MOMENT_DATE_FORMATS` can be automatically provided by importing
// `MatMomentDateModule` in your applications root module. We provide it at the component level
// here, due to limitations of our example generation script.
{
  provide: DateAdapter,
  useClass: MomentDateAdapter,
  deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS],
},
{ provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS }]

And here is a stackblitz example to show you the whole code.

Answered By – trisek

Answer Checked By – Timothy Miller (AngularFixing Admin)

Leave a Reply

Your email address will not be published.