I'm working on an Angular App with Material Design, and I'm using Moment.js to parse and format dates.
In one of my pages I have a Material's Datepicker. I have followed the material's guide-lines to make the Datepicker work with moment object - instead on the native Date object.
Also I managed to display the Date in the Datepicker in a certain format. But this format in hard coded in the Component's providers. How can I change the format during run-time, according to the user preferences?
Here is what I have this far:
I've installed npm's packages:
$ npm i moment -S
$ npm i @angular/material-moment-adapter -S
// app.module.ts
import { MatMomentDateModule } from '@angular/material-moment-adapter'
...
@NgModule({
imports: [
MatMomentDateModule,
...
// demo.component.ts
import * as moment from 'moment';
import { MAT_DATE_FORMATS } from '@angular/material/core';
const MY_FORMATS = {
parse: {
dateInput: 'LL',
},
display: {
dateInput: 'LL',
monthYearLabel: 'MMM YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'MMMM YYYY',
},
};
@Component({
selector: 'app-demo',
templateUrl: './demo.component.html',
styleUrls: ['./demo.component.scss'],
providers: [
{ provide: MAT_DATE_FORMATS, useValue: MY_FORMATS },
],
})
export class DemoComponent {
public dateVal = moment();
}
// demo.component.html
<mat-form-field>
<input matInput [matDatepicker]="myDatePicker" [(ngModel)]="dateVal">
<mat-datepicker-toggle matSuffix [for]="myDatePicker"></mat-datepicker-toggle>
<mat-datepicker #myDatePicker></mat-datepicker>
</mat-form-field>
As you can see, the date-format is defined in the Component's providers. How can I change this in run-time?
A working example could be found here:
https://stackblitz.com/angular/mgaargebgpd?file=app%2Fdatepicker-formats-example.ts