Search code examples
angulartypescriptangular-materialdatepickerdate-range

How to clear mat-date-range-input selection on the calendar?


I ran into a weird issue I cannot seem to find a solution for. I have a mat date range picker, Angular Typescript.

I have a function where I want to clear any selection. But my problem is that the code below does clear the date(s), confirmed by console.log, but the selection of dates remain selected on the calendar when I open the calendar again after clearing.

HTML

  <mat-form-field class="datePickerForm">
                <mat-date-range-input [formGroup]="range" [rangePicker]="picker" [disabled]="isDateRangeDisabled" #dateRangeInput>
                    <input matStartDate formControlName="start" placeholder="Select date range" (dateChange)="onDateFilter($event)" #startDate>
                    <input matEndDate formControlName="end" placeholder="" (dateChange)="onDateFilter($event)" #endDate>
                  </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>

TS Clear function

@ViewChild('startDate') startDateRef: ElementRef;
@ViewChild('endDate') endDateRef: ElementRef;

 range = new FormGroup({
         start: new FormControl(),
         end: new FormControl(),
 });

...
this.startDate = undefined;
this.endDate = undefined;
this.startDateRef.nativeElement.value = '';
this.endDateRef.nativeElement.value = '';
this.range.value.start = null;
this.range.value.end = null;
...

For reference, onDateFilter() change event code

onDateFilter(event) {
this.startDate = moment(this.range.value.start).format('YYYY-MM-DDT00:00:00.000') + 'Z'
this.endDate = moment(this.range.value.end).format('YYYY-MM-DDT23:59:59.000') + 'Z'

this.validateDateRange(this.startDate, this.endDate);
}

Actual

enter image description here

Expected

enter image description here


Solution

  • Managed to find the answer upon posting.

    this.range.reset();
    

    The form group has a reset function, clearing the calendar selection.