Home  >  Angular  >  Angular Material

Angular Material Datepicker : Date Range

By Arvind Rai, June 26, 2020
This page will walk through Angular Material Datepicker with date range. Date range functionality in Datepicker has been introduced in Angular 10. To select a date range instead of a single date, we need to create Datepicker using <mat-date-range-picker>, <mat-date-range-input> and <mat-datepicker-toggle> elements. The <mat-date-range-input> consists two text input, one for start date and another for end date. The start date is lesser than end date and this is validated by matStartDateInvalid and matEndDateInvalid error attributes.
On this page we will create a complete example with reactive form. The form will contain two Datepicker with date range. On form submit we will fetch their values.

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

Creating Datepicker with Date Range

To create Datepicker we need to import MatDatepickerModule in our application module.
import { MatDatepickerModule } from '@angular/material/datepicker'; 
To run our Datepicker, we also need to provide DateAdapter and for this we can import MatNativeDateModule, MatMomentDateModule, or we can provide a custom implementation. In our example we are importing MatNativeDateModule.
import { MatNativeDateModule } from '@angular/material/core'; 
A Datepicker is created with text input. So we also need to import MatInputModule in our application module.
import { MatInputModule } from '@angular/material/input'; 
Now find the code to create Datepicker with date range.
<mat-form-field>
  <mat-label>Choose Date Range</mat-label>
  <mat-date-range-input [rangePicker]="myRangePicker">
    <input matStartDate placeholder="Start date">
    <input matEndDate placeholder="End date">
  </mat-date-range-input>
  <mat-datepicker-toggle matSuffix [for]="myRangePicker"></mat-datepicker-toggle>
  <mat-date-range-picker #myRangePicker></mat-date-range-picker>
</mat-form-field> 
To create Datepicker with date range, we are using following elements.
<mat-date-range-picker>: This element creates the popup panel for selecting the date range. It acts same as <mat-datepicker> element.

<mat-date-range-input>: It requires two input text, for start and end date. We need to bind rangePicker property in this element. The input text for start date, uses matStartDate attribute and for end date input text, uses matEndDate attribute.

<mat-datepicker-toggle>: This element adds a toggle button to Datepicker.

Validating and Getting Date Range with FormGroup

To validate start date and end date in Datepicker date range, Angular material provides matStartDateInvalid and matEndDateInvalid error attributes.
Suppose we want to fetch data using FormGroup.
studentForm = this.formBuilder.group({
  admDateRange: this.formBuilder.group({
    startDate: '',
    endDate: ''
  }),
  ------
}); 
We create and validate start date and end date of Datepicker as following.
<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-error *ngIf="studentForm.get('admDateRange').get('startDate').hasError('matStartDateInvalid')">
    Invalid start date
  </mat-error>
  <mat-error *ngIf="studentForm.get('admDateRange').get('endDate').hasError('matEndDateInvalid')">
    Invalid end date
  </mat-error>    
</mat-form-field> 

Complete Example

Here we will create a reactive form with two date fields with date range.
student.component.html
<h3>Datepicker with Date Range</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>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-error *ngIf="studentForm.get('admDateRange').get('startDate').hasError('matStartDateInvalid')">
      Invalid start date
    </mat-error>
    <mat-error *ngIf="studentForm.get('admDateRange').get('endDate').hasError('matEndDateInvalid')">
      Invalid end date
    </mat-error>    
  </mat-form-field>
  <br/>
  <mat-form-field>
    <mat-label>School Session Range</mat-label>
    <mat-date-range-input [rangePicker]="sessionRangePicker" formGroupName="sessionRange">
      <input matStartDate formControlName="startDate" placeholder="Start date">
      <input matEndDate formControlName="endDate" placeholder="End date">
    </mat-date-range-input>
    <mat-datepicker-toggle matSuffix [for]="sessionRangePicker"></mat-datepicker-toggle>
    <mat-date-range-picker #sessionRangePicker></mat-date-range-picker>
  
    <mat-error *ngIf="studentForm.get('sessionRange').get('startDate').hasError('matStartDateInvalid')">
        Invalid start date
    </mat-error>
    <mat-error *ngIf="studentForm.get('sessionRange').get('endDate').hasError('matEndDateInvalid')">
        Invalid end date
    </mat-error>    
  </mat-form-field>
  <br/><br/>
  <button mat-raised-button>Submit</button>
</form> 
student.component.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { StudentService } from './student.service';

@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: '',
    admDateRange: this.formBuilder.group({
      startDate: '',
      endDate: ''
    }),
    sessionRange: this.formBuilder.group({
      startDate: '',
      endDate: ''
    })
  });
  onFormSubmit() {
    this.studentService.saveStudent(this.studentForm.value);
    this.studentForm.reset();
  }
} 
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 { MatNativeDateModule } from '@angular/material/core';

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

@NgModule({
  declarations: [
    AppComponent,
    StudentComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    BrowserAnimationsModule,
    MatInputModule, 
    MatDatepickerModule,
    MatNativeDateModule
  ],
  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. 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 : Date Range
We can select date range as following.
Angular Material Datepicker : Date Range

Reference

Datepicker

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI








©2020 concretepage.com | Privacy Policy | Contact Us