angular-material-components
angular-material-components copied to clipboard
Set date and time format at runtime
To format the date and time from the date and time picker we need to create a const with the desired date and time format like this:
const CUSTOM_MOMENT_FORMATS: NgxMatDateFormats = {
parse: {
dateInput: "L, LT"
},
display: {
dateInput: "DD/MM/YYYY HH:mm",
monthYearLabel: "MMM YYYY",
dateA11yLabel: "LL",
monthYearA11yLabel: "MMMM YYYY"
}
};
And in the @Component section it needs to be set as provider like this:
providers: [
{ provide: NGX_MAT_DATE_FORMATS, useValue: CUSTOM_MOMENT_FORMATS } // Custom Date Format
]
But how can I set the date and time format dynamically. For example I have set the date and time format in the user settings and want to use this format here.
Instead of using useValue in @Component providers, do useClass:
providers: [
{ provide: NGX_MAT_DATE_FORMATS, useClass: CustomDateFormat } // Custom Date Format
]
Define the class with internal variable and getters for display and parse:
export class CustomDateFormat {
format = true;
constructor() { }
get display() {
return {
dateInput: this.format ? 'l, LTS' : 'l',
monthYearLabel: 'MMM YYYY',
dateA11yLabel: 'L',
monthYearA11yLabel: 'MMMM YYYY',
}
}
get parse() {
return { dateInput: this.format ? 'l, LTS' : 'l' }
}
}
Inject the provider to constructor of your component to access to the variable 'format':
constructor(@Inject(NGX_MAT_DATE_FORMATS) public config: CustomDateFormat) { }
Now you can change the formats inside your component , like:
const ONLYDATE = false, DATEANDTIME = true;
this.config.format = ONLYDATE;
this.config.format = DATEANDTIME;