Angular Material Custom Date Picker with MomentJS

Photo by Olya Kobruseva from Pexels

First Step

Install momentjs with npm.

npm install moment --save  

Install momentjs adapter

npm install --save @angular/material-moment-adapter

Now update tsconfig.json

Add the following line under compilerOptions

"allowSyntheticDefaultImports": true,

Add DatePipe to the root or feature module. In the this example in the app.module.ts file.

import { DatePipe } from '@angular/common';

Under the providers section in the app.module.ts.

  imports: [
   BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    HttpClientModule,
    HttpClientJsonpModule,
    FormsModule,
    ReactiveFormsModule
  ],

  providers: [
    DatePipe
  ],

Finally, restart your app with ng s and add the following to your component

import {Component} from '@angular/core';
import {FormControl} from '@angular/forms';
import {MomentDateAdapter, MAT_MOMENT_DATE_ADAPTER_OPTIONS} from '@angular/material-moment-adapter';
import {DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from '@angular/material/core';
import {MatDatepicker} from '@angular/material/datepicker';

// Depending on whether rollup is used, moment needs to be imported differently.
// Since Moment.js doesn't have a default export, we normally need to import using the `* as`
// syntax. However, rollup creates a synthetic default module and we thus need to import it using
// the `default as` syntax.
import * as _moment from 'moment';
// tslint:disable-next-line:no-duplicate-imports
import {default as _rollupMoment, Moment} from 'moment';

const moment = _rollupMoment || _moment;

// See the Moment.js docs for the meaning of these formats:
// https://momentjs.com/docs/#/displaying/format/
export const MY_FORMATS = {
  parse: {
    dateInput: 'MM/YYYY',
  },
  display: {
    dateInput: 'MM/YYYY',
    monthYearLabel: 'MMM YYYY',
    dateA11yLabel: 'LL',
    monthYearA11yLabel: 'MMMM YYYY',
  },
};

Now you can follow this example from angular material’s documentation

https://stackblitz.com/angular/xkqdxaroyol?file=src%2Fapp%2Fdatepicker-views-selection-example.ts