Issue
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?
Solution
So i didn't knew if you used the MatNativeDateModule
that you could also implement a custom date adapter. I thought this was something that was specific to MatMomentDateModule
.
Once I figured this out i could just overwrite the format function and format it manually likes so:
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;
}
}
And implement it like so:
@NgModule({
providers: [
{
provide: DateAdapter,
useClass: AppDateAdapter,
deps: [MAT_DATE_LOCALE, Platform]
},
]
})
export class AppModule { }
Answered By - Martijn van den Bergh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.