Angular Material 9|8 Datepicker Tutorial with Examples

In this article, we will discuss the Angular Material 8/9 Datepicker tutorial. We will develop an Angular application and learn how to add the Material UI library to use Datepickers.

Angular Material is a UI library which provides several useful and Angular compatible UI components. Material’s latest version 9 can be easily installed by running a single NPM command in Angular CLI command line.

Angular Material Datepicker is implemented by adding the mat-datepicker directive in the template. For using the Material date picker, we first need to import the MatDatePicker module which provides datepicker services.

Datepickers can be opened on input on places inline for date selection. We will discuss all these examples in this tutorial.

Also, discuss some tricks to solve some basic challenges like

  • How to open Datepicker on Input focus?
  • How to Set Min and Max date in Datepicker?
  • Change Material Datepicker view to Year or Month by default.

Let’s get started!

# Create a new Angular project

Before, creating a new project make sure you have the latest version of Angular CLI installed. You can update it by executing the following NPM command.

$ ng update @angular/cli @angular/core

To create a new Angular project, run following command and answer for questions to configure the project.

$ new angular-material-data-table

#? Would you like to add Angular routing? No
#? Which stylesheet format would you like to use? CSS

Now go to project root by running

$ cd angular-material-data-table

You can open the project in VS code(if installed) by running:

$ code .

Install and configure Angular Material library

To install the Material library, run following NPM command in the terminal

$ ng add @angular/material

Select a material theme for the project from the option list

? Choose a prebuilt theme name, or "custom" for a custom theme: (Use arrow keys)
> Indigo/Pink        [ Preview: https://material.angular.io?theme=indigo-pink ]
  Deep Purple/Amber  [ Preview: https://material.angular.io?theme=deeppurple-amber ]
  Pink/Blue Grey     [ Preview: https://material.angular.io?theme=pink-bluegrey ]
  Purple/Green       [ Preview: https://material.angular.io?theme=purple-green ]
  Custom

Answer for Material typography styles in Yes or No. You can read more about it here.

? Set up global Angular Material typography styles? No

Select if you want to enable Browser Animation support. If selected Yes, it will automatically import the BrowserAnimationsModule in app.module.ts file in the Angular project.

? Set up browser animations for Angular Material? Yes

That's it we are done with Angular project and its configuration of Material support. Now you can run Angular application by executing below command

$ ng serve --open

 

# Using Material modules in the Angular project

For implementing Material UI components in an Angular project, we need to import API modules of that particular component in the application's module.

Open the app.module.ts file and update the file as shown below

//app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { 
  MatDatepickerModule,
  MatNativeDateModule,
  MatInputModule
} from '@angular/material';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,

    MatNativeDateModule,
    MatInputModule,
    MatDatepickerModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

# Adding Material Datepicker in Component

Now we are ready to start testing our first and most basic Datepicker implementation in app.component.html file

  <input matInput [matDatepicker]="picker" placeholder="Choose a date">
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
Material Datepicker consists of two things, an input field, and a calender popup.The matDatepicker property is used to connect these two with a template variable (#picker).

# Custom Toggle Icon

To toggle Calander popup, mat-datepicker-toggle is used to show/hide calendar which can have matDatepickerToggleIcon as a child to show custom icon.
    <input matInput [matDatepicker]="myicon" placeholder="Custom Icon Datepicker">
    <mat-datepicker-toggle matSuffix [for]="myicon">
      <mat-icon matDatepickerToggleIcon>settings</mat-icon>
    </mat-datepicker-toggle>
    <mat-datepicker #myicon></mat-datepicker>

Note: To use mat-icon, add MatIconModule in app.module.ts file's imports array and also include following material icons google fonts in the index.html. Check more material icons here

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

# Set Start Date in Calander

The [startAt] property is used to set a start date on <mat-datepicker>
<mat-datepicker #picker [startAt]="startDate"></mat-datepicker>
startDate = new Date(1990, 0, 1);

 

# Change Calander Popup View

The startView property of <mat-datepicker> can be used to show a month, year, or multi-year for selection where month is a default
startView="year"
startView="multi-year"

# Validation on Datepicker

Datepicker can have three types of validation properties Min, Max and matDatepickerFilter available for Input field control

Using Min & Max Dates

Using min and max properties of Input field we can ser range of dates to make the selection available. A user cannot move before minand move after a max date.

<input matInput [min]="minDate" [max]="maxDate" [matDatepicker]="picker" placeholder="Choose a date">
  minDate = new Date(1985, 4, 12); 
  maxDate = new Date(1985, 4, 22);

# Disable Somedays from Angular Material Datepicker using Filter

The matDatepickerFilter property of Input accepts a function which returns true or false for a date in calendar popup. If it returns false for a date it will be shown a disabled for selection.

Advantage of using Filter over Min, Max is that user can move over a period of dates even if disabled which is unlike behavior for previous validation.

<input matInput [matDatepicker]="picker" [matDatepickerFilter]="onlyOdds" placeholder="Choose an Odd date">
  onlyOdds = (d: Date): boolean => {
    const date = d.getDate(); 
    // Even dates are disabled.
    return date % 2 == 0;
  }

# Change Event for Datepicker

There are two events available for Input field (dateInput) and (dateChange)
(dateInput): Event fired when the user changes values by typing in Input or select date from the calendar
(dateChange): Event fired on blur after the user changes the value in Input and also after the date is changed from the calendar
<input matInput [matDatepicker]="picker" placeholder="Input & change events" (dateInput)="inputEvent($event)" (dateChange)="changeEvent($event)">
  inputEvent(event){
    // Return date object 
    console.log(event.value);
  }
  changeEvent(event){
    // Return date object
    console.log(event.value);
  }

 

# ReadOnly or Disabled datepicker

disabled property can be added to all or any of the three <input>, <mat-datepicker-toggle> or <mat-datepicker>

To make it read-only or disabled just add it to all of them

    <input matInput [matDatepicker]="picker" placeholder="Read only date" [disabled]="true">
    <mat-datepicker-toggle matSuffix [for]="picker" [disabled]="true">
    </mat-datepicker-toggle>
    <mat-datepicker #picker [disabled]="true"></mat-datepicker>

 

Conclusion: So here we discussed Angular Material 8 Datepicker and it's important properties available. We can also customize its template and have custom date format using momentjs. Check out more on docs here

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments