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</pre> To create a new Angular project, run following command and answer for questions to configure the project. <pre class="wp-block-prismatic-blocks"><code class="language-javascript">$ new angular-material-data-table #? Would you like to add Angular routing? No #? Which stylesheet format would you like to use? CSS</pre> Now go to project root by running <pre class="wp-block-prismatic-blocks"><code class="language-javascript">$ cd angular-material-data-table</pre> You can open the project in VS code(if installed) by running: <pre class="wp-block-prismatic-blocks"><code class="language-javascript">$ code .</pre> Install and configure Angular Material library To install the Material library, run following NPM command in the terminal <pre class="wp-block-prismatic-blocks"><code class="language-javascript">$ ng add @angular/material</pre> Select a material theme for the project from the option list <pre class="wp-block-prismatic-blocks"><code class="language-javascript">? 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</pre> Answer for Material typography styles in Yes or No. You can read more about it <a href="https://material.io/develop/web/components/typography/" target="_blank" rel="nofollow noopener noreferrer">here</a>. <pre class="wp-block-prismatic-blocks"><code class="language-javascript">? Set up global Angular Material typography styles? No</pre> Select if you want to enable Browser Animation support. If selected Yes, it will automatically import the <code>BrowserAnimationsModule
in app.module.ts file in the Angular project.? Set up browser animations for Angular Material? Yes</pre> 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 <pre class="wp-block-prismatic-blocks"><code class="language-javascript">$ ng serve --open</pre> <h3># Using Material modules in the Angular project</h3> 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 <strong>app.module.ts</strong> file and update the file as shown below <div> <pre class="lang:js mark:10-14,25-27 decode:true">//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 { } </pre> <h2></h2> <h3># Adding Material Datepicker in Component</h3> Now we are ready to start testing our first and most basic Datepicker implementation in <strong>app.component.html</strong> file <pre><code class="language-markup"> <input matInput [matDatepicker]="picker" placeholder="Choose a date"> <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle> <mat-datepicker #picker></mat-datepicker></pre> <div> <div></div> <div>Material Datepicker consists of two things, an <code>input
field, and a calender popup.ThematDatepicker
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 havematDatepickerToggleIcon
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></pre> <a href="https://www.freakyjolly.com/wp-content/uploads/2019/07/angular-material-datepicker-basic-custom-icon.jpg"><img class="aligncenter size-full wp-image-2614" src="https://www.freakyjolly.com/wp-content/uploads/2019/07/angular-material-datepicker-basic-custom-icon.jpg" alt="" width="247" height="49" /></a> <strong>Note</strong>: To use mat-icon, add <em>MatIconModule </em>in app.module.ts file's imports array and also include following material icons google fonts in the <em>index.html. </em>Check more material icons <a href="https://material.io/tools/icons/" target="_blank" rel="noopener noreferrer">here</a> <pre><code class="language-markup"><link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"></pre> <h3></h3> <h3># Set Start Date in Calander</h3> <div> <div>The <code>[startAt]
property is used to set a start date on<mat-datepicker>
<mat-datepicker #picker [startAt]="startDate"></mat-datepicker> </pre> <pre class="wp-block-prismatic-blocks"><code class="language-javascript">startDate = new Date(1990, 0, 1);</pre> </div> <h3># Change Calander Popup View</h3> <div> <div>The <code>startView
property of<mat-datepicker>
can be used to show a month, year, or multi-year for selection where month is a defaultstartView="year"
startView="multi-year"
# Validation on Datepicker
Datepicker can have three types of validation propertiesMin
,Max
andmatDatepickerFilter
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 beforemin
and move after amax
date.<input matInput [min]="minDate" [max]="maxDate" [matDatepicker]="picker" placeholder="Choose a date"></pre> <pre class="wp-block-prismatic-blocks"><code class="language-javascript"> minDate = new Date(1985, 4, 12); maxDate = new Date(1985, 4, 22);</pre> <a href="https://www.freakyjolly.com/wp-content/uploads/2019/07/angular-material-datepicker-min-max.jpg"><img class="aligncenter size-full wp-image-2617" src="https://www.freakyjolly.com/wp-content/uploads/2019/07/angular-material-datepicker-min-max.jpg" alt="" width="215" height="216" /></a> <h3></h3> <h3><strong># Disable Somedays from Angular Material Datepicker using Filter</strong></h3> The <code>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"></pre> <pre class="wp-block-prismatic-blocks"><code class="language-javascript"> onlyOdds = (d: Date): boolean => { const date = d.getDate(); // Even dates are disabled. return date % 2 == 0; }</pre> <a href="https://www.freakyjolly.com/wp-content/uploads/2019/07/angular-material-datepicker-filter.jpg"><img class="aligncenter size-full wp-image-2618" src="https://www.freakyjolly.com/wp-content/uploads/2019/07/angular-material-datepicker-filter.jpg" alt="" width="213" height="224" /></a> </div> <div> <h3></h3> <h3></h3> <h3># Change Event for Datepicker</h3> </div> <div></div> <div>There are two events available for Input field <code>(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 calendarTo make it read-only or disabled just add it to all of them<input matInput [matDatepicker]="picker" placeholder="Input & change events" (dateInput)="inputEvent($event)" (dateChange)="changeEvent($event)"></pre> <pre class="wp-block-prismatic-blocks"><code class="language-javascript"> inputEvent(event){ // Return date object console.log(event.value); } changeEvent(event){ // Return date object console.log(event.value); }</pre> <h3># ReadOnly or Disabled datepicker</h3> disabled property can be added to all or any of the three <code><input>
,<mat-datepicker-toggle>
or<mat-datepicker>
<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
It works great!! But I have a table so I have added the date picker on a the table header. The date picker calender is showed under the table. Why is that?