Home > OS >  Material date range picker set end date on focus out
Material date range picker set end date on focus out

Time:08-16

I am using material date range picker (https://material.angular.io/components/datepicker) and I have the requirement that when user selects start date and clicks outside the picker (focusout) without selecting end date, that end date should be set to the value of start date automatically.

Is there any way to do this?

CodePudding user response:

I followed an approach similar to this answer to a related solution.

In the HTML I declared the start and end date inputs with an id, to be able to later identify them (<input matStartDate #dateRangeStart />).

Then, in the mat-date-range-picker I used the output event closed (read api) to get the event when you click outside the picker and it gets closed. I passed the two dates using their ids like (closed)="closed(dateRangeStart, dateRangeEnd)".

<mat-form-field appearance="standard">
  <mat-date-range-input [rangePicker]="dateRangePicker">
    <input matStartDate #dateRangeStart />
    <input
      matEndDate
      #dateRangeEnd
    />
  </mat-date-range-input>
  <mat-datepicker-toggle matPrefix [for]="dateRangePicker">
  </mat-datepicker-toggle>
  <mat-date-range-picker
    #dateRangePicker
    (closed)="closed(dateRangeStart, dateRangeEnd)"
  ></mat-date-range-picker>
</mat-form-field>

Then, in the .ts file I declared the function that is fired when closing, which checks if the end date is not set, and if so, sets it to the value of the start date:

closed(dateRangeStart: HTMLInputElement, dateRangeEnd: HTMLInputElement) {
    if (!dateRangeEnd.value) {
      dateRangeEnd.value = dateRangeStart.value;
    }
  }

I attach a demo stackblitz

Hope helps!

CodePudding user response:

Try this

<mat-form-field appearance="fill">
  <mat-label>Enter a date range</mat-label>
  <mat-date-range-input [rangePicker]="picker">
    <input matStartDate placeholder="Start date" [formControl]="startDate">
    <input matEndDate placeholder="End date" [formControl]="endDate">
  </mat-date-range-input>
  <mat-hint>MM/DD/YYYY – MM/DD/YYYY</mat-hint>
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-date-range-picker #picker (closed)="close()"></mat-date-range-picker>
</mat-form-field>
export class DateRangePickerOverviewExample {
  startDate = new FormControl<Date | null>(null);
  endDate = new FormControl<Date | null>(null);
  close(): void {
    if (!this.endDate.value && this.startDate.value) {
      this.endDate.setValue(this.startDate.value);
    }
  }
}

https://stackblitz.com/edit/angular-kuit1s?file=src/app/date-range-picker-overview-example.ts

  • Related