I'm working at an Angular9 app that works with dates.
It displays and updates several <mat-datepicker>
fields.
I am using a custom MAT_DATE_FORMATS
and MomentDateAdapter
(@angular/material-moment-adapter
) from https://www.npmjs.com/package/@angular/material-moment-adapter.
I'm using the following code which works okay:
export const APP_MOMENT_DATE_FORMATS =
{
parse: {},
display: {
dateInput: 'YYYY/MM/DD/MM',
monthYearLabel: 'MMM YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'MMMM YYYY'
}
};
//..
providers: [
{
provide: MAT_DATE_FORMATS, useValue: APP_MOMENT_DATE_FORMATS
},
{
provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE]
}
]
// ..
Stackblitz demo: https://stackblitz.com/edit/angular-formatted-datepicker-vdtaqj?file=app%2Fdatepicker-overview-example.ts
Now, I was wondering if I could update the value of the APP_MOMENT_DATE_FORMATS.display.dateInput
dynamically - eg: maybe it will be setted from a configuration service via a http request, or maybe I will display a selector in the interface.
example:
export const APP_MOMENT_DATE_FORMATS =
{
// ..
display: {
dateInput: this.appService.dateInputFormat,
// ..
}
};
I know that I could implement a custom date adapter, as described here: Angular 2 Material 2 datepicker date format.
But I was wondering if there is another method to do it, without implementing a new custom date adapter.
Thanks.
After spending hours looking for solution, I come up the below solution by just simply injecting MAT_DATE_FORMATS and change it dynamically:
const APP_MOMENT_DATE_FORMATS =
{
parse: {
dateInput: 'MM/DD/YYYY',
},
display: {
dateInput: 'MM/DD/YYYY',
monthYearLabel: 'MMM YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'MMMM YYYY'
}
};
@Component({
...
providers: [
{
provide: MAT_DATE_FORMATS, useValue: APP_MOMENT_DATE_FORMATS
},
{
provide: DateAdapter,
useClass: MomentDateAdapter,
deps: [MAT_DATE_LOCALE]
}
]
})
export class DatePickerComponent implements OnInit, OnDestroy {
constructor(@Inject(MAT_DATE_FORMATS) public data: any) {
data.parse.dateInput = 'DD/MM/YYYY'
data.display.dateInput = 'DD/MM/YYYY'
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With