0

I have implemented the Angular Material Date picker, and wish to filter the days that can be picked. So I want the user to select a date then only be able a range of 21 days after the start date or less.

I was considering to have two date fields, but the client wants the date range look and feel.

But it seems like the dateRange does not have the filter function. How would i approach this?

  • before Material Angular 10, there're no date range and so many people make one. I think that the best bet is looking for one of this. The problem with Angular material date picker is that you can not make a "custom day", so you can use renderer2 and document.query to get the days. I don't know if can help you this SO: https://stackoverflow.com/questions/60247962/angular-material-datepicker-with-range-selection/60258340#60258340. NOTE: There are' better implementation of date range that mine – Eliseo Oct 08 '20 at 17:07
  • another aproach: https://stackoverflow.com/questions/64521480/angular-material-datepicker-limit-the-range-selection/64525438#64525438 – Eliseo Oct 25 '20 at 15:34

1 Answers1

0

So I got a simple solution, Where i still allowed the user to select more than 21 days, then after the second date selection just bring it back to 21 days and set the selector to the new end date.

The HTML code

    <mat-date-range-input  [min]="minDate" [max]="maxDate"  [rangePicker]="picker"   >
      <input matStartDate placeholder="Start date" formControlName="checkin">
      <input matEndDate  placeholder="End date" formControlName="checkout" [ngModel]="calculateDays()">
    </mat-date-range-input>

The TS code

calculateDays(): void{
let days = (this.searchForm.value.checkout - this.searchForm.value.checkin) / 86400000;
if(days > 21){
  this.searchForm.value.checkout = new Date(this.searchForm.value.checkin);
  this.searchForm.value.checkout.setDate(this.searchForm.value.checkout.getDate() + 21);
    this.searchForm.controls.checkout.patchValue(this.searchForm.value.checkout);
    days = 21;
  }
  if(days > 0){
    this.days = days;
  }
}