Skip to main content

Angular(Version 10) Date Picker Range Selection In Angular Material UI


In Angular Material Version 10, announced a new feature in date selection is Date Picker Range Selection. Before Angular V10 for date range selection need to write custom code or need to use third-party plugins. So now by upgrading to Angular V10, we can grab this new feature of a Date Range selection.

Default Core Components Of Date Range Selection:

The default core component of date range selection of Date Picker in Angular Material is:
  • mat-date-range-picker
  • mat-date-range-input
mat-date-range-picker is an Angular Material Component for date range selection. mat-date-range-picker component is shown popup calendar like mat-datepicker component but allows multi-date selection option.

mat-date-range-input is an Angular Material Component for the date range selection. This component requires to input fields to capture the start date and end date that are selected from mat-date-rang-picker.

Create Sample Angular(V10) Application:

Let's create a sample application to implement the date range selection date picker. Not to forgot this sample example only works with Angular v10.
Skip this section if you know how to create angular application and configure angular material
Commands:
Run this command to install Angular CLI command on your system:

npm install -g @angular/cli
Run this Angular CLI command to generate angular application:

ng new your-project-name
Run the following command to add Angular Material:

ng add @angular/material
Run the following command to start angular application:

ng serve

Add Date Range Selection Material Component:

Now to add material date picker with date range selection to it, then we need to add material components as below.
src/app/app.component.html:
<mat-form-field >
  <mat-label>Enter a date range</mat-label>
  <mat-date-range-input  [rangePicker]="myPicker">
    <input matStartDate placeholder="Start date">
    <input matEndDate placeholder="End date">
  </mat-date-range-input>
  <mat-datepicker-toggle matSuffix [for]="myPicker"></mat-datepicker-toggle>
  <mat-date-range-picker #myPicker></mat-date-range-picker>
</mat-form-field>
  • #L1 at this line mat-form-field is an angular material component for form fields
  • #L2 at this line mat-label is an angular material component to represent HTML labels
  • #L3-#L6 at these lines mat-date-range-input is an angular material component for date range selection. This component renders with 2 input fields inside of it. These 2 input fields used to capture date range selection values like start and end dates. These 2 input fields decorated with directives like matStartDate and matEndDate to respond for date picker selection. mat-date-range-input component makes communication with mat-date-range-picker component by using [rangePicker] directive, to this [rangePicker] directive we need to assign template variable(in our example myPicker is template variable of mat-date-range-picker).
  • #L7 at this line mat-datepicker-toggle is an angular material component represents calendar icon inside the input field and on clicking this icon calendar will toggle. To appear this icon to the rightmost side of the input filed needs to use the matSuffix directive. mat-datepicker-toggle also configure with [for] directive which has the value of template variable(in our example myPicker is template variable of mat-date-range-picker).
  • #L8 at this line mat-date-range-picker is an angular material component that shows a calendar popup with a date range selection feature.

Import Material Modules:

Now before the test, our date picker needs to load a few angular material modules like below.
  • MatFormFieldModule
  • MatDatePickerModule
  • MatNativeDateModule
src/app/app.module.ts:
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatNativeDateModule } from '@angular/material/core';
// code hidden for display pupose
@NgModule({
  imports: [
    MatDatepickerModule,
    MatFormFieldModule,
    MatNativeDateModule
  ],
})
export class AppModule {}
Now, let's run the application and output shows as below.

Reactive Form Implementation For Date Range Selection:

Let's write a sample example to use this date range selection date picker in angular reactive forms implementation.

The first step to import ReactiveFormsModule from the '@angular/forms' package.
src/app/app.module.ts:
import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports: [
    ReactiveFormsModule
  ]
})
export class AppModule {}
// code hidden for display purpose
Now to create FormGroup or FormControl instances it easy to do by importing FormBuilder instance.
src/app/app.component.ts:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  dateSelectorGroup:FormGroup;
  displayStartDate:string = "N/A";
  displayEndDate:string = "N/A";
 
  constructor(private fb:FormBuilder) {
    
  }
  ngOnInit(): void {
    this.initializeForm();
  }

  initializeForm(){
    this.dateSelectorGroup = this.fb.group({
      startDate:[''],
      endDate:['']
    });

    this.dateSelectorGroup.controls.startDate.valueChanges.subscribe(value => {
      if(value){
        this.displayStartDate = value;
      }
      else{
        this.displayStartDate = "N/A"
      }
    });

    this.dateSelectorGroup.controls.endDate.valueChanges.subscribe(value => {
      if(value){
        this.displayEndDate = value;
      }
      else{
        this.displayEndDate = "N/A"
      }
    })
  }
}
  • #L2 at this line FormBuilder, FormGroup instances are importing from '@angular/forms' package
  • #L10 at this line initialized a variable 'dateSelectorGroup' of type FormGroup, this FormGroup variable is used in the Html component to establish a reactive form communication.
  • #L11-L12 at these lines declared variables like 'displayStartDate', 'displayEndDate'. The idea behind to declare these variables to assign the date picker selected values to display.
  • #L14 at this line FormBuilder injected into the component constructor.
  • #L21-L44 at these lines method like 'initializeform()' setup to add reactive form and register the form control change events.
  • #L22-25 at these lines FormGroup instance created from FormBuilder and assigned to 'dateSelectorGroup' variable.
  • #L27-34  at these lines capturing the value change event of 'startDate' form control and assigning the changed value to 'displayStartDate' variable.
  • #L36-43  at these lines capturing the value change event of 'endDate' form control and assigning the changed value to 'displayEndDate' variable.
src/app/app.component.html:
<mat-form-field >
  <mat-label>Enter a date range</mat-label>
  <mat-date-range-input [formGroup]="dateSelectorGroup"  [rangePicker]="myPicker">
    <input matStartDate formControlName="startDate" placeholder="Start date">
    <input matEndDate formControlName="endDate" placeholder="End date">
  </mat-date-range-input>
  <mat-datepicker-toggle matSuffix [for]="myPicker"></mat-datepicker-toggle>
  <mat-date-range-picker #myPicker></mat-date-range-picker>
</mat-form-field>
<div>
  <div>
    <span>State Date:</span> <span>{{displayStartDate}}</span>
  </div>
  <div>
    <span>End Date:</span> <span>{{displayEndDate}}</span>
  </div>
</div>
  • #L3 at this line FromGroupDirective was declared by assigning the 'dateSelectorGroup' variable
  • #L4-L5 at these lines FormControlDirectives was declared on input fields
  • #L10-L17 at these line angular interpolation binding was performed to display selected dates.
Now run the application then select the start and end dates and output shows as below.

Wrapping Up:

Hopefully, I think this article delivered some useful information on the Date Picker Range Selection In Angular Material(V10). I love to have your feedback, suggestions, and better techniques in the comment section below.

Follow Me:

Comments