Home  >  Angular  >  Angular Material

Angular Material Datepicker : Disable Past and Future Dates

By Arvind Rai, July 14, 2020
This page will provide how to disable past and future dates in Angular Material Datepicker calendar. We can disable dates using following Datepicker input text properties.
1. Using min and max properties
2. Using matDatepickerFilter property.

The min configures minimum date to be selected and max configures maximum date to be selected. The same can be achieved by matDatepickerFilter property. The matDatepickerFilter can also be used to disable any specific day or month such as disable weekends in every month.
Here on this page we will provide complete example to disable past and future dates using native JavaScript Date as well as Moment.


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

Disable Past and Future Dates with min and max

To disable past and future dates, we can use min and max properties in Datepicker input text with matInput attribute.
Disable only past dates
If only past dates need to be disabled, configure only min property.
Disable only future dates
If only future dates need to disabled, configure only max property.

To disable past and future dates both we need to configure min and max both. Here we will provide code with Moment and Date both.
1. Using Moment : When we create our Datepicker with MatMomentDateModule, we need to set minimum and maximum dates using Moment. Find the code snippet of component.
minDate: Moment;
maxDate: Moment;
ngOnInit() {
 const currentYear = moment().year();
 this.minDate = moment([currentYear - 1, 0, 1]);
 this.maxDate = moment([currentYear + 1, 11, 31]);
} 
Find the HTML code to configure min and max properties in Datepicker input text.
<mat-form-field appearance="fill">
  <mat-label>Date of Birth</mat-label>
  <input matInput [matDatepicker]="dob" [min]="minDate" [max]="maxDate" formControlName="dateOfBirth">
  <mat-datepicker-toggle matSuffix [for]="dob"></mat-datepicker-toggle>
  <mat-datepicker #dob startView="multi-year"></mat-datepicker>
</mat-form-field> 
In the above code the property binding of min is with component property minDate and property binding of max is with component property maxDate. Suppose current year is 2020. Then we can select calendar date from 01-Jan-2019 to 31-Dec-2021.
Angular Material Datepicker : Disable Past and Future Dates
We can set year, month and day according to our requirement. Find one more date to set.
this.minDate = moment([currentYear - 1, 5, 10]);
this.maxDate = moment([currentYear + 1, 8, 20]); 
In the above code minimum date is 10-Jun-2019 and maximum date is 20-Sep-2021. The rest past and future dates will be disabled.

2. Using native JavaScript Date : When we create our Datepicker with MatNativeDateModule, we need to set minimum and maximum dates using native JavaScript Date. Find the code snippet of component.
minDate: Date;
maxDate: Date;
ngOnInit() {
  const currentYear = new Date().getFullYear();
  this.minDate = new Date(currentYear - 1, 0, 1);
  this.maxDate = new Date(currentYear + 1, 11, 31);
} 
Find the HTML code snippet.
<mat-form-field appearance="fill">
  <input matInput [matDatepicker]="dob" [min]="minDate" [max]="maxDate" formControlName="dateOfBirth">
  ------
</mat-form-field> 

Disable Past and Future Dates with matDatepickerFilter

We can use matDatepickerFilter to disable past and future dates. The matDatepickerFilter is used as property binding with Datepicker input text.
Suppose we are using MatMomentDateModule to create Datepicker. Create a function as below using Moment in the component.
currentYear = moment().year();
myDateFilter = (m: Moment | null): boolean => {
  const year = (m || moment()).year();
  return year >= this.currentYear -1 && year <= this.currentYear + 1;
} 
Suppose current year is 2020. We can select minimum date as 1-Jan-2019 and maximum date as 31-Dec-2021.
The HTML code will be as following.
<mat-form-field appearance="fill">
  <mat-label>Date of Admission</mat-label>
  <input matInput [matDatepicker]="dtAdm" [matDatepickerFilter]="myDateFilter" formControlName="dateOfAdmission">
  <mat-datepicker-toggle matSuffix [for]="dtAdm"></mat-datepicker-toggle>
  <mat-datepicker #dtAdm startView="multi-year"></mat-datepicker>
</mat-form-field> 
Disable only past dates
myDateFilter = (m: Moment | null): boolean => {
  const year = (m || moment()).year();
  return year >= this.currentYear -1;
} 
Disable only future dates
myDateFilter = (m: Moment | null): boolean => {
  const year = (m || moment()).year();
  return year <= this.currentYear + 1;
} 

2. When we create Datepicker using MatNativeDateModule then use native JavaScript Date to disable past and future dates.
currentYear = new Date().getFullYear();
myDateFilter = (d: Date | null): boolean => {
  const year = (d || new Date()).getFullYear();
  return year >= this.currentYear -1 && year <= this.currentYear + 1;
} 

Disable Weekends

To disable any specific month or day in every year or to disable any specific date conditionally, we can use matDatepickerFilter property. For example we are disabling the weekends for every month in our below code.
Find the code using Moment.
myDateFilter = (m: Moment | null): boolean => {
  const day = (m || moment()).day();
  return day !== 0 && day !== 6;
} 
Now find the code using native JavaScript Date.
myDateFilter = (d: Date | null): boolean => {
  const day = (d || new Date()).getDay();
  return day !== 0 && day !== 6;
} 
Find the HTML code snippet.
<mat-form-field appearance="fill">
  <input matInput [matDatepicker]="dtAdm" [matDatepickerFilter]="myDateFilter" formControlName="dateOfAdmission">
  ------
</mat-form-field> 
Find the print screen of calendar.
Angular Material Datepicker : Disable Past and Future Dates

Complete Example

Here we will provide complete demo application to disable past and future dates of Datepicker calendar using moment.js.
student.component.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { StudentService } from './student.service';
import * as _moment from 'moment';
import { Moment } from 'moment';

const moment = _moment;

@Component({
  selector: 'app-student',
  templateUrl: './student.component.html'
})
export class StudentComponent implements OnInit {
  minDate: Moment;
  maxDate: Moment;
  myDateFilter = (m: Moment | null): boolean => {
    const dateNum = (m || moment()).date();
    return dateNum >= 10 && dateNum <= 25;
  } 
  constructor(private formBuilder: FormBuilder, private studentService: StudentService) { }
  ngOnInit() {
    const currentYear = moment().year();
    this.minDate = moment([currentYear - 1, 5, 10]);
    this.maxDate = moment([currentYear + 1, 8, 20]);
  }
  studentForm = this.formBuilder.group({
    name: '',
    dateOfBirth: '',
    dateOfAdmission: ''
  });
  onFormSubmit() {
    this.studentService.saveStudent(this.studentForm.value);
    let dateOfBirth: Moment = this.studentForm.get('dateOfBirth').value;
    console.log(dateOfBirth.toObject());
    let yearOfBirth = dateOfBirth.toObject().years;
    console.log('yearOfBirth : ', yearOfBirth);
    this.studentForm.reset();
  }
} 
student.component.html
<h3>Datepicker : Disable Dates</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 appearance="fill">
    <mat-label>Date of Birth</mat-label>
    <input matInput [matDatepicker]="dob" [min]="minDate" [max]="maxDate" formControlName="dateOfBirth">
    <mat-datepicker-toggle matSuffix [for]="dob"></mat-datepicker-toggle>
    <mat-datepicker #dob startView="multi-year"></mat-datepicker>
  </mat-form-field>  
  <br/>
  <mat-form-field appearance="fill">
    <mat-label>Date of Admission</mat-label>
    <input matInput [matDatepicker]="dtAdm" [matDatepickerFilter]="myDateFilter" formControlName="dateOfAdmission">
    <mat-datepicker-toggle matSuffix [for]="dtAdm"></mat-datepicker-toggle>
    <mat-datepicker #dtAdm ></mat-datepicker>
  </mat-form-field>    
  <br/><br/>
  <button mat-raised-button>Submit</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 {
} 
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 } 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 { } 

Run Application

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

References

Datepicker
Moment.js Documentation

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI








©2020 concretepage.com | Privacy Policy | Contact Us