Issue: Inconsistency with Angular Material 7 DatePicker and moment js integration
Challenge: The datepickers fail to update their locale when the language of the web application is changed.
Objective: I aim to have my date pickers automatically adjust to the selected language's format whenever a change in language occurs within my application. Currently, I find myself switching between dd/MM/yyyy and MM/dd/yyyy manually.
Seeking Guidance: As a newcomer to moment, I'm struggling to implement the necessary formatting adjustments. Any helpful pointers would be greatly appreciated.
Sample HTML code:
<mat-form-field>
<mat-label>From date</mat-label>
<input name="fromDate" [min]="minDate" [max]="maxDate" [formControl]="displayFromDate"
matInput [matDatepicker]="fromDatePicker">
<mat-datepicker-toggle matSuffix [for]="fromDatePicker"></mat-datepicker-toggle>
<mat-datepicker #fromDatePicker disabled="false"></mat-datepicker>
</mat-form-field>
Snippet from translation service that switches moment locale based on language selection: The 'lang' parameter toggles between 'en' and 'fr', controlled by an app switch.
public use(lang: string): void {
this._currentLang = lang;
moment.locale(lang);
this.currentLang$.next(this.currentLang);
}
App.module.ts excerpt:
import { MAT_MOMENT_DATE_FORMATS, MomentDateAdapter } from '@angular/material-moment-adapter';
import { DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE } from '@angular/material/core';
import localeFr from '@angular/common/locales/fr';
import localeEn from '@angular/common/locales/en';
registerLocaleData(localeFr);
registerLocaleData(localeEn);
...
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
...
{ provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] },
{ provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS },],
Component snippet utilizing the datepicker:
this.translationService.currentLang$.subscribe(currentLang => {
this.displayFromDate = new FormControl({ value: moment(this.displayFromDate.value).format(), disabled: true });
console.log('displayFromDate', this.displayFromDate);
});