Home  >  Angular  >  Angular Material

Angular Material Datepicker using Moment

By Arvind Rai, July 03, 2020
This page will walk through Angular Material Datepicker using moment.js. Angular material provides MatMomentDateModule API that uses moment.js to create Datepicker. To create a Datepicker, we need DateAdapter and that can be provided by MatNativeDateModule, MatMomentDateModule, or a custom implementation. The MatNativeDateModule uses native JavaScript Date and MatMomentDateModule uses moment from moment.js. The MatMomentDateModule has advantage over MatNativeDateModule. This is because MatNativeDateModule uses native JavaScript Date and it cannot set parse format. The MomentDateAdapter or a custom DateAdapter can set parse format.
Here on this page we will provide a complete example to create Datepicker using moment.js.

Technologies Used

Find the technologies being used in our example.
1. Angular 10.0.0
2. Angular Material 10.0.0
3. Node.js 12.5.0
4. NPM 6.9.0
5. moment.js 2.27.0

Install moment.js

The moment.js is a JavaScript library that can be used in place of native JavaScript Date. The moment.js library is the wrapper on native JavaScript Date. The moment.js is free and open source JavaScript library.
Angular MatMomentDateModule internally imports Moment from moment.js and we need to install it in our application.
We can install moment.js as following.
npm install moment --save 

Using MatMomentDateModule

To use Datepicker with moment.js we need to import MatMomentDateModule in our application module.
import { MatInputModule } from '@angular/material/input';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatMomentDateModule } from '@angular/material-moment-adapter';

@NgModule({
  imports: [
    ------
    MatInputModule, 
    MatDatepickerModule,
    MatMomentDateModule,
  ],
  -------
})   
export class AppModule { } 
Now we can create Datepicker as following.
<mat-form-field>
  <mat-label>Date of Birth</mat-label>
  <input matInput [matDatepicker]="dob" formControlName="dateOfBirth">
  <mat-datepicker-toggle matSuffix [for]="dob"></mat-datepicker-toggle>
  <mat-datepicker #dob></mat-datepicker>
</mat-form-field> 

Using MAT_MOMENT_DATE_ADAPTER_OPTIONS :

The MomentDateAdapter parses date in our time zone specific locale, by default. We can change it to UTC by providing MAT_MOMENT_DATE_ADAPTER_OPTIONS by setting useUtc: true.
Import MAT_MOMENT_DATE_ADAPTER_OPTIONS as following.
import { MAT_MOMENT_DATE_ADAPTER_OPTIONS } from '@angular/material-moment-adapter'; 
Set useUtc to true.
providers: [
  {provide: MAT_MOMENT_DATE_ADAPTER_OPTIONS, useValue: {useUtc: true}}
] 
By default the MAT_MOMENT_DATE_ADAPTER_OPTIONS parses dates in forgiving way. To parse date strictly, we can use strict: true.
providers: [
  {provide: MAT_MOMENT_DATE_ADAPTER_OPTIONS, useValue: {strict: true}}
] 

Setting Date with Moment

Find the code to set Date in Datepicker using moment at runtime in our component.
Import moment.
import * as _moment from 'moment';
const moment = _moment; 
Now call moment as following.
admDateRange: {
  startDate: moment([2020, 5, 1]),  //yyyy, mm, dd
  endDate: moment([2020, 5, 25])
} 

Complete Example

app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule }    from '@angular/forms'; 
import { MatInputModule } from '@angular/material/input';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatMomentDateModule, MAT_MOMENT_DATE_ADAPTER_OPTIONS } from '@angular/material-moment-adapter';

import { AppComponent } from './app.component';
import { StudentComponent } from './student.component';

@NgModule({
  declarations: [
    AppComponent,
    StudentComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    BrowserAnimationsModule,
    MatInputModule, 
    MatDatepickerModule,
    MatMomentDateModule,
  ],
  providers: [
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule { } 
student.component.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl } from '@angular/forms';
import { StudentService } from './student.service';

import * as _moment from 'moment';

const moment = _moment;

@Component({
  selector: 'app-student',
  templateUrl: './student.component.html'
})
export class StudentComponent implements OnInit {
  constructor(private formBuilder: FormBuilder, private studentService: StudentService) { }
  ngOnInit() {
  }
  studentForm = this.formBuilder.group({
    name: '',
    dateOfBirth: '',
    admDateRange: this.formBuilder.group({
      startDate: '',
      endDate: ''
    })
  });
  onFormSubmit() {
    this.studentService.saveStudent(this.studentForm.value);
    this.studentForm.reset();
  }
  setDefaultDate() {
    this.studentForm.patchValue({
      dateOfBirth: moment([2005, 10, 27]), //yyyy, mm, dd
      admDateRange: {
        startDate: moment([2020, 5, 1]),
        endDate: moment([2020, 5, 25])
      }
    });
  }
} 
student.component.html
<h3>Datepicker with Moment</h3>
<form [formGroup]="studentForm" (ngSubmit)="onFormSubmit()">
  <mat-form-field>
    <mat-label>Student Name</mat-label>
    <input matInput formControlName="name">
  </mat-form-field>
  <br/>
  <mat-form-field>
    <mat-label>Date of Birth</mat-label>
    <input matInput [matDatepicker]="dob" formControlName="dateOfBirth">
    <mat-datepicker-toggle matSuffix [for]="dob"></mat-datepicker-toggle>
    <mat-datepicker #dob></mat-datepicker>
  </mat-form-field>
  <br/>
  <mat-form-field>
    <mat-label>Admission Date Range</mat-label>
    <mat-date-range-input [rangePicker]="admDateRangePicker"  formGroupName="admDateRange">
      <input matStartDate formControlName="startDate" placeholder="Start date">
      <input matEndDate formControlName="endDate" placeholder="End date">
    </mat-date-range-input>
    <mat-datepicker-toggle matSuffix [for]="admDateRangePicker"></mat-datepicker-toggle>
    <mat-date-range-picker #admDateRangePicker></mat-date-range-picker>
  </mat-form-field>
  <br/><br/>
  <button mat-raised-button>Submit</button>
  <button mat-raised-button type="button" (click)="setDefaultDate()">Set Default Dates</button>
</form> 
student.service.ts
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class StudentService {
  saveStudent(student) {
    console.log(JSON.stringify(student));
  }
} 
app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
      <app-student></app-student>
  `
})
export class AppComponent {
} 

Run Application

To run the application, find the steps.
1. Install Angular CLI using link.
2. Install Angular Material using link.
3. Download source code using download link given below on this page.
4. Use downloaded src in your Angular CLI application.
5. Run ng serve using command prompt.
6. Access the URL http://localhost:4200
Find the print screen of the output.
Angular Material Datepicker using Moment

References

Datepicker
Moment.js

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI








©2020 concretepage.com | Privacy Policy | Contact Us