HowcanIformattheAngularMaterialdatepickerwithoutmoment.jsdependency
What do I want to achieve?
I want my Angular Material(v11) datepicker to use the DD-MM-YYYY format in an Angular version 11 project.
What have I tried?
I tried using the MatMomentDateModule but this uses the moment.js library. This in turn will use all the locales in the bundle, which inceases the bundle size with 400kb. I have added CUSTOM_DATE_FORMATS to the providers of my app.module.ts which looks like this:
const CUSTOM_DATE_FORMATS = {
parse: {
dateInput: 'DD-MM-YYYY',
},
display: {
dateInput: 'DD-MM-YYYY',
monthYearLabel: 'MMMM YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'MMMM YYYY',
},
};
And this works but as mentioned before, the bundle size increases severely and i don't use any locales.
Is there a way to do format my date DD-MM-YYYY, without the use of the moment.js library?
or
Is the moment.js treeshakable in a way so that i only use the stuff that i need?
回答
所以我不知道你是否使用了MatNativeDateModule你也可以实现自定义日期适配器。我认为这是特定于MatMomentDateModule.
一旦我想通了这一点,我就可以覆盖格式化函数并手动格式化它,如下所示:
export class CustomDateAdapter extends NativeDateAdapter {
format(date: Date, displayFormat: any): string {
const days = date.getDate();
const months = date.getMonth() + 1;
const year = date.getFullYear();
return days + '-' + months + '-' + year;
}
}
并像这样实现它:
@NgModule({
providers: [
{
provide: DateAdapter,
useClass: AppDateAdapter,
deps: [MAT_DATE_LOCALE, Platform]
},
]
})
export class AppModule { }