Customizing the parse and display formats of Material Datepicker using momentjs
Code In Action @StackBlitz
Prerequisites
- Create a new Angular Project refer Angular Step by Step
- Add Material For the Project refer Material for Angular
- Dependencies
- MomentJS
- Material-moment-adapter
Add Dependencies
for Moment run the below command in Integrated Terminal
npm i --save moment
npm i --save @angular/material-moment-adapter
TSConfig.JSON
Add "allowSyntheticDefaultImports":false in compiler options.
Allow default imports from modules with no default export.This does not affect code emit, just typechecking.
CustomDateFormat.ts
Add a new file named CustomDateFormat.ts and copy the below code.
import * as _moment from 'moment';
import {default as _rollupMoment} from 'moment';
import {MomentDateAdapter} from '@angular/material-moment-adapter';
export const moment = _rollupMoment || _moment;
export const DD_MMM_YYYY = {
parse: {
dateInput: 'LL',
},
display: {
dateInput: 'DD-MMM-YYYY',
monthYearLabel: 'MMM YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'MMMM YYYY',
},
};
Implementation
In required component (HTML) add Mat Date picker
<mat-form-field> <input matInput [matDatepicker]="dp" placeholder="Verbose datepicker" (dateChange)="DateChangeEvent('change', $event)" [(ngModel)]="date1" > <mat-datepicker-toggle matSuffix [for]="dp"> </ mat-datepicker-toggle> <mat-datepicker #dp ></mat-datepicker> < / mat-form-field>Add the below code in component.ts file
import { Component } from '@angular/core';
import { DD_MMM_YYYY,moment } from './CustomDateFormat'
import {MomentDateAdapter} from '@angular/material-moment-adapter';
import {DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from '@angular/material/core';
import {MatDatepickerInputEvent} from '@angular/material/datepicker';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ],
providers: [
{provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE]},
{provide: MAT_DATE_FORMATS, useValue: DD_MMM_YYYY},
]
})
export class AppComponent {
name = 'Angular';
public date1: any = moment();
public setdate: Date = new Date(2018,0,1);
public datefromcontrol: Date ;
DateChangeEvent(type: string, event: MatDatepickerInputEvent) {
console.log(this.date1);
this.datefromcontrol=new Date(this.date1.year(), this.date1.month(), this.date1.date());
console.log(this.datefromcontrol);
}
setinputdate() {
this.date1 = moment().date( this.setdate.getDay() ).year(this.setdate.getFullYear()).month(this.setdate.getMonth());
}
}
0 Comments