Disable all days after an amount of days in date range picker angular material

142 views Asked by At

I am using angular (the latest version 16) material date range picker with the action buttons active like the image suggests 3rd SEP

Now I want to disable a certain number of days following the start date selected. Imagine I want to disable all days after 4 days from the start date. It would result in something like

10th March

Although, angular (I believe) doesn't have a way to get the internal state, because the inputs just change after the Apply button is clicked.

This is the html I am using,

<mat-form-field class="custom-datepicker">
    <mat-date-range-input
      [formGroup]="dateFilterForm"
      [rangePicker]="rangePicker"
      [max]="currentDate"
    >
      <input
        #matStartDate
        matStartDate
        placeholder="Start date"
        formControlName="start"
      />
      <input
        #matEndDate
        matEndDate
        placeholder="End date"
        formControlName="end"
      />
    </mat-date-range-input>
    <mat-datepicker-toggle matSuffix [for]="rangePicker"></mat-datepicker-toggle>
    <mat-date-range-picker #rangePicker>
      <mat-date-range-picker-actions>
        <button mat-button matDateRangePickerCancel i18n="@@cancel">Cancel</button>
        <button
          mat-raised-button
          color="primary"
          matDateRangePickerApply
          (click)="onSelectDate(0)"
        >
          Apply
        </button>
      </mat-date-range-picker-actions>
    </mat-date-range-picker>
  </mat-form-field>

I tried to use dateChange and dateInput and then used my own filter function on the date picker. However, these events only emit after the user presses the Apply button. So I don't have the first date pressed by the user to disabled the days I want

1

There are 1 answers

2
Gaurav Verma On

I would suggest create a function to calculate n days later date and pass that date into your TS variable.

 this.setMaxToDate(noOfDays){
 const laterDate = new Date().setTime(new Date(this.startDate).getTime() 
 + (noOfDays * 24 * 60 * 60 * 1000));
  this.maxDate = new Date(laterDate);
 }
   

Then pass this variable in mat-date-range-input's input property "max" and call the function on start date change

<mat-form-field>
  <mat-label>Enter a date range</mat-label>
  <mat-date-range-input [rangePicker]="picker" [max]="maxDate">
    <input matStartDate placeholder="Start date" 
   (dateChange)="setMaxToDate(4)">
    <input matEndDate placeholder="End date">
  </mat-date-range-input>
  <mat-hint>MM/DD/YYYY – MM/DD/YYYY</mat-hint>
  <mat-datepicker-toggle matIconSuffix [for]="picker"></mat- 
  datepicker- 
  toggle>
  <mat-date-range-picker #picker></mat-date-range-picker>
</mat-form-field>