How to listen for DatePicker date range changed

Viewed 286

Is it possible to listen for a date range changed event on the Material Datepicker?

Currently, I use a workaround where I listen for (dateChange) for both start and end. Then I need to check that none of them are null and finally call my event handler onRangeChanged(start: Date, end: Date).

From full sample:

    <mat-form-field>
      <mat-label>Enter a date range</mat-label>
      <mat-date-range-input [rangePicker]="picker">
        <input matStartDate placeholder="Start date" (dateChange)="onStartDateChange($event)">
        <input matEndDate placeholder="End date" (dateChange)="onEndDateChange($event)">
      </mat-date-range-input>
      <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
      <mat-date-range-picker #picker></mat-date-range-picker>
    </mat-form-field>
  onStartDateChange(e: MatDatepickerInputEvent<Date, Date>) {
    if (e && e.value) {
      this.start = e.value;
    }
    this.checkRange();
  }

  onEndDateChange(e: MatDatepickerInputEvent<Date, Date>) {
    if (e && e.value) {
      this.end = e.value;     
    }
    this.checkRange();
  }

  checkRange(): void {
    if (this.start != null && this.end != null) {
      this.onRangeChanged(this.start, this.end);
    }
  }

  // Is it possible to have the DatePicker directly call this event handler?
  onRangeChanged(start: Date, end: Date) {
  }

Sidenote:

In the docs I found a MatDateSelectionModel<S, D> that potentially could give me a single DateRange at once, but I do not understand how to use it.

0 Answers
Related