I need to display dates in two different formats based on some user settings.
Let's say "YYYY-MM-DD" and "DD/MM/YYYY".
I know that I have to write a custom DateAdapter (I've already done that), but is it possible to switch between the two formats with e.g. a dropdown list?
P.S.
I'm also using Moment.js.
Add a comment
|
2 Answers
Your custom date format is in a TS file.
This means you have access to Javascript and Typescript.
What you could do is use the localStorage to store the format, and in your date format :
export const CUSTOM_DATE_FORMAT = {
parse: {
dateInput: localStorage.getItem('dateFormat'),
},
display: {
dateInput: localStorage.getItem('dateFormat'),
monthYearLabel: 'MMMM YYYY',
dateA11yLabel: 'DD/MM/YYYY',
monthYearA11yLabel: 'MMMM YYYY',
},
};
I think you'll figure out how to store the formatin the local storage ;)
2 Comments
jeti
Thanks, it works! Have you got maybe an idea, how to do it without reloading the window? If no, I'll accept this answer as it definitely works.
Below you can see a custom adpater using the local storage. In this way, you don't have to reload the window.
import { MomentDateAdapter, MatMomentDateAdapterOptions } from "@angular/material-moment-adapter";
import { Moment } from "moment";
import { UserService } from "app/core/api/user.service";
export class CustomDateAdapter extends MomentDateAdapter {
parse(value: any, parseFormat: string | string[]): Moment | null {
let dateFormat: string | string[] = localStorage.getItem("dateFormat") || parseFormat;
return super.parse(value, dateFormat);
}
format(date: Moment, displayFormat: string): string {
let dateFormat: string | string[] = localStorage.getItem("dateFormat") || displayFormat;
return super.format(date, dateFormat);
}
}
And in your module:
....
import { MAT_DATE_FORMATS } from '@angular/material/core';
import { MatMomentDateModule, MAT_MOMENT_DATE_ADAPTER_OPTIONS, MomentDateAdapter, MAT_MOMENT_DATE_FORMATS } from '@angular/material-moment-adapter';
import { CustomDateAdapter } from 'app/material/custom-date-adapter';
....
providers: [
{ provide: DateAdapter, useClass: CustomDateAdapter },
{ provide: MAT_MOMENT_DATE_ADAPTER_OPTIONS, useValue: { useUtc: true } },
{ provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS }
]})
export class MaterialModule { }
Please notice that this example uses the momentjs implementation of the DateAdapter.