Mat date start date end date validation angular 8

Mr.M picture Mr.M · Apr 2, 2020 · Viewed 12.4k times · Source

I am working on Mat date picker where I have start date and end date where I have one validation that is end date should not be lesser than start date for example

if start date was 12-JAN-2020 end date can be 12-JAN-2020 or greater than this but it can not be 11-JAN-2020.

Currently I was trying with Min MAX but this is not working as expected

I was trying in google & SO not getting correctly

   <mat-form-field>
      <input matInput [matDatepicker]="fromDate" placeholder="Choose a date"
          [value]="getData(item2.firstPatientInDate)" [max]="today<item2.lastPatientInDate|| item2.lastPatientInDate == undefined?today:item2.lastPatientInDate" [(ngModel)]="item2.firstPatientInDate">
                    <mat-datepicker-toggle matSuffix [for]="pickerstart"></mat-datepicker-toggle>
                    <mat-datepicker #picker></mat-datepicker>
                </mat-form-field>

        <mat-form-field>
           <input matInput [matDatepicker]="pickerend" [max]="today" [min]="item2.firstPatientInDate"   placeholder="Choose a date"
                        [value]="getData(item2.lastPatientInDate)" [(ngModel)]="item2.lastPatientInDate">
                    <mat-datepicker-toggle matSuffix [for]="pickerend"></mat-datepicker-toggle>
                    <mat-datepicker #picker1></mat-datepicker>

                </mat-form-field>

Answer

Harsh picture Harsh · Apr 2, 2020

You can find a working sample in below link:

stackblitz: angular material start-end date sample

TypeScript file

import {Component} from '@angular/core';
import {FormControl} from '@angular/forms';

@Component({
  selector: 'datepicker-value-example',
  templateUrl: 'datepicker-value-example.html',
  styleUrls: ['datepicker-value-example.css'],
})
export class DatepickerValueExample {
  startDate = new FormControl(new Date());
  endDate = new FormControl(new Date());
}

HTML file

<mat-form-field>
  <input matInput [matDatepicker]="picker1" placeholder="Start Date" [formControl]="startDate">
  <mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle>
  <mat-datepicker #picker1></mat-datepicker>
</mat-form-field>

<mat-form-field>
  <input matInput [matDatepicker]="picker2" placeholder="End Date"
   [min]="startDate.value" [formControl]="endDate">
  <mat-datepicker-toggle matSuffix [for]="picker2"></mat-datepicker-toggle>
  <mat-datepicker #picker2></mat-datepicker>
</mat-form-field>