How to implement angular material datepicker in Angular 12 | 13 .?

We have started a series of tutorials on Angular material design components. In this article, we’ll explore and learn Angular material datepicker. In our previous articles, we learned how to implement Angular date picker.

In this tutorial, we have three objective, first learn how to use Angular material datepicker, secondly how to add our own custom date format for material datepicker and last add date filter like min and max attributes of Angular material.

Setting up and configuring Angular material datepicker project

Let’s first create our Angular material datepicker project. In our previous articles, we learned how to install and the best approach to configuring Angular material in our project. Run the following command to create and add Angular Material to our project.

ng new angularMaterialDateApp
cd angularMaterialDateApp
ng add @angular/material

// Add this two libraries
npm install moment --save
npm install @angular/material/moment-adapter --save

While running the 3rd command will ask you the select theme, material typography, and animation, press yes on all. To use the Angular material component, we have to import it into our app module. It is good practice to have a separate module for Angular material. Let’s create a module and import all material components on it.

ng g m ng-material
Angular material datepicker example

Open src/app/ng-material/ng-material.module.ts and replace the existing code with the code shown below.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MAT_DATE_FORMATS } from '@angular/material/core';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button'
import { MatMomentDateModule } from '@angular/material-moment-adapter';

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    MatDatepickerModule,
    MatFormFieldModule,
    MatDatepickerModule,
    MatFormFieldModule,
    MatInputModule,
    MatButtonModule,
    MatDatepickerModule,
    MatFormFieldModule,
    MatInputModule,
    MatButtonModule,
    MatMomentDateModule,
  ],
  exports: [
    MatDatepickerModule,
    MatFormFieldModule,
    MatInputModule,
    MatButtonModule,
    MatDatepickerModule,
    MatFormFieldModule,
    MatInputModule,
    MatButtonModule,

    MatMomentDateModule,
  ]
})
export class NgMaterialModule { }

We are importing all the required modules in our custom material module file. Now we need to import our material module and ReactiveFormModule in the /app/app.module.ts file.

import { NgMaterialModule } from './ng-material/ng-material.module';
@NgModule({
...
imports: [
   ...
  ReactiveFormsModule,
  NgMaterialModule,
],
})

How to use Angular material datepicker?

We had successfully configured the Angular material datepicker application, now we can use the material date picker component.

Angular material datepicker example

We will demonstrate a few examples of the material date pickers, let’s first demonstrate a simple example.

Angular material datepicker example

In our app.component.ts file, we have created a form and let add a code form field.

...
import * as moment from 'moment';
...
export class AppComponent {
  form = new FormGroup({});
  
  constructor(private fb: FormBuilder) { }

  ngOnInit(): void {
    this.form = this.fb.group({
      date1: new FormControl(new Date()),
    });
  }
}

In our component template, let’s add the material date picker component.

 <form [formGroup]="form" (ngSubmit)="onSubmit()">
   <mat-form-field appearance="outline">
     <mat-label>Datepicker example</mat-label>
     <input matInput [max]="dateMaxDate" [min]="dateMinDate" 
     [matDatepicker]="matDate3Picker" formControlName="date3" />
     <mat-datepicker-toggle matSuffix [for]="matDate3Picker">
     </mat-datepicker-toggle>
     <mat-datepicker #matDate3Picker></mat-datepicker>
   </mat-form-field>
 </form>

The material datepicker comes with a calendar icon, we don’t need to add an icon. Material date picker has the following components.

Component NameDescription
mat-datepickerThe datepicker component allows users to enter a date either through text input or by choosing a date from the calendar.
mat-datepicker-toggleThis component is optional that gives the user an easy way to open the datepicker pop-up.
inputA datepicker is composed of text input and a calendar pop-up, connected via the matDatepicker property on the text input.

Angular material datepicker format

By default material, the date picker has a date format of M/d/yyyy, we can add our own custom date format. Angular Material provides MAT_DATE_FORMATS object and it is a collection of formats used by Datepicker to parse and display dates. To use our own custom date format, we have to override the default format of MAT_DATE_FORMATS.

Let’s create a class called custom-date-formats.ts inside our ng-material folder src/app/ng-material/custom-date-formats.ts

export const CUSTOM_DATE_FORMATS = {
    parse: {
        dateInput: 'LL',
      },
      display: {
        dateInput: 'LL',
        monthYearLabel: 'MMM YYYY',
        dateA11yLabel: 'LL',
        monthYearA11yLabel: 'MMMM YYYY',
      },
}; 

Now we have to add our custom date format class in the provider, let’s add this in our material module, ng-material/ng-material.module.ts file as.

....
import { MAT_DATE_FORMATS } from '@angular/material/core';
import { CUSTOM_DATE_FORMATS } from './custom-date-formats';

@NgModule({
  declarations: [],
  imports: [
   ...
  ],
  exports: [
    ...
  ],
  providers: [
    { provide: MAT_DATE_FORMATS, useValue: CUSTOM_DATE_FORMATS }
  ],
})
export class NgMaterialModule { }

When working with material datepicker, we have to import two modules.

  1. MatDatePickerModule: For material datepicker UI control.
  2. MatNativeDateModule: It use javascript date object implementation.

We have installed two libraries along with Material. The moment is a popular javascript library for implementing date and time. Angular Material uses DateAdapter of the following options NativeDateAdapter, MomentDateAdapter, or custom DateAdapter. The JavaScript default implementation does not include all locales around the world. Hence we have imported MatMomentDateModule.

How to add min and max properties

The min and max properties allow us to add data validation to the date picker input. These properties will disable all dates in the calendar that are before the min and after the max value.

Angular material datepicker min and max properties

We can see that date before Dec 12, 2019, but we can’t select it. Because we had added min and max properties on the material date picker. Let’s edit our typescript to add value for min and max.

dateMaxDate = new Date();
dateMinDate = new Date('12.12.2019')
form = new FormGroup({});

constructor(private fb: FormBuilder) {}

ngOnInit(): void {
  this.form = this.fb.group({
    date3: new Date(),
   });
}

In our component template let’s add datepicker component and min, and max properties.

<mat-form-field appearance="outline">
  <mat-label>Datepicker example</mat-label>
   <input matInput [max]="dateMaxDate" [min]="dateMinDate"    
     [matDatepicker]="matDate3Picker" formControlName="date3" />
   <mat-datepicker-toggle matSuffix [for]="matDate3Picker"></mat-datepicker-toggle>
  <mat-datepicker #matDate3Picker></mat-datepicker>
</mat-form-field>

Angular material datepicker switcher

The mat-datepicker component, have three different date switcher, it allows us easily change the date between, day, month, or year.

We can see different Angular material datepicker switcher, the first is the default, the second is based on month and the last is based on year.

....
export class AppComponent {
  form = new FormGroup({});

  constructor(private fb: FormBuilder) { }

  ngOnInit(): void {
    this.form = this.fb.group({
      date1: new FormControl(new Date()),
      date2: new FormControl(new Date()),
      date3: new Date(),
    });
  }

  onSubmit() {
    console.log(this.form.value);
  }
}
<div class="container">
  <h2>Angular material date switcher</h2>
  <form [formGroup]="form" (ngSubmit)="onSubmit()">

    <mat-form-field appearance="outline">
      <mat-label>Default day switcher</mat-label>
      <input matInput [matDatepicker]="datepicker" formControlName="date1">
      <mat-datepicker-toggle matSuffix [for]="datepicker"></mat-datepicker-toggle>
      <mat-datepicker #datepicker [opened]="true"></mat-datepicker>
    </mat-form-field>

    <mat-form-field appearance="outline">
      <mat-label>Year base date switcher</mat-label>
      <input matInput [matDatepicker]="matDatepicker" formControlName="date2">
      <mat-datepicker-toggle matSuffix [for]="matDatepicker"></mat-datepicker-toggle>
      <mat-datepicker #matDatepicker startView="year" [opened]="true"></mat-datepicker>
    </mat-form-field>

    <mat-form-field appearance="outline">
      <mat-label>Multiple year date switcher</mat-label>
      <input matInput [matDatepicker]="matDate3Picker" formControlName="date3" />
      <mat-datepicker-toggle matSuffix [for]="matDate3Picker"></mat-datepicker-toggle>
      <mat-datepicker #matDate3Picker [opened]="true"></mat-datepicker>
    </mat-form-field>
      
    <button mat-raised-button color="primary" type="submit">
      Submit
    </button>
  </form>
</div>
Check articles on the best and latest 2022, and 2021 Angular books to read for your journey from beginner to advanced level. BEST BOOK ON ANGULAR 2022 – 2021


Conclusion

We have completed our Angular material datepicker tutorial, and we have learned how to use the material datepicker component and its properties. I hope you have got some ideas.

Related Articles

Spread the love

1 thought on “How to implement angular material datepicker in Angular 12 | 13 .?”

  1. Thanks for your article.

    Small correction: you have:
    npm install @angular/material/moment-adapter –save
    This should be :
    npm install @angular/material-moment-adapter –save

Leave a Comment

Your email address will not be published.

Scroll to Top