1

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.

Stefan
  • 50
  • 1
  • 10

1 Answers1

2

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.

trisek
  • 701
  • 6
  • 14
  • 1
    If i put it in the Component itself it works, thanks! Unfortunately it doesn't work if the MomentDateAdapter is in the AppModule. – Stefan Sep 20 '21 at 10:18
  • It should work in the same way, I updated a [stackblitz example](https://stackblitz.com/edit/angular-dbfyvb?file=src%2Fmain.ts) in a way that `MomentDateAdapter` is now in the root `NgModule`. – trisek Sep 20 '21 at 12:53
  • Tried again. In my case, `MomentDateAdapter` had to be put in the parent module of the component. – Stefan Sep 20 '21 at 14:28