I am trying to reset the content of a mat-date-range-input, but cannot find how
The input itself looks like this :
<mat-form-field appearance="fill" >
<mat-label>Date</mat-label>
<mat-date-range-input [rangePicker]="datePicker" disabled >
<input matStartDate #dateStart placeholder="Start">
<input matEndDate #dateEnd placeholder="End" (dateChange)="dateChange(dateStart.value, dateEnd.value)">
</mat-date-range-input>
<mat-datepicker-toggle matSuffix [for]="datePicker"></mat-datepicker-toggle>
<mat-date-range-picker #datePicker [calendarHeaderComponent]="calendarHeader" disabled="false">
<mat-datepicker-actions>
<button mat-button matDatepickerCancel>Cancel</button>
<button mat-raised-button matDatepickerApply>Ok</button>
</mat-datepicker-actions>
</mat-date-range-picker>
</mat-form-field>
I would like to be able to reset it with a button, which would trigger a function (which also reset multiple other fields, and some data, omitted in this question. As such, the reset has to be on the Typescript side).
I already tried multiples solution (ViewChild, bindings, etc.) found here and there (Stackoverflow as well as dozen of blogs found via google), but none of those solutions worked. I'm still new to Angular, so it may be just me who badly implemented those solutions, so if you think one of the solutions I tried is the good one, do not hesitate to post it.
CodePudding user response:
<input matStartDate #startDate>
<input matEndDate #endDate>
...
<button mat-button (click)="startDate.value = ''; endDate.value = ''">reset</button>
CodePudding user response:
You can use the formgroup
to make thing work and if you want to reset, just set the value for start, end to null or whatever you want to make it default;
HTML PART:
<mat-form-field appearance="fill">
<mat-label>Enter a date range</mat-label>
<mat-date-range-input [formGroup]="range" [rangePicker]="picker">
<input matStartDate formControlName="start" placeholder="Start date">
<input matEndDate formControlName="end" placeholder="End date">
</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></mat-date-range-picker>
<mat-error *ngIf="range.controls.start.hasError('matStartDateInvalid')">Invalid start date</mat-error>
<mat-error *ngIf="range.controls.end.hasError('matEndDateInvalid')">Invalid end date</mat-error>
</mat-form-field>
<input type="button" value="reset" (click)="resetRange()" >
<p>Selected range: {{range.value | json}}</p>
TS Part:
range = new FormGroup({
start: new FormControl<Date | null>(null),
end: new FormControl<Date | null>(null),
});
resetRange() {
this.range.patchValue({
start: null,
end: null,
});
}
Here is Example