My HTML code is:
<mat-form-field appearance="fill">
<mat-label>Enter a date range</mat-label>
<mat-date-range-input [rangePicker]="picker">
<input matStartDate placeholder="Start date" #startDateInput />
<input matEndDate placeholder="End date" #endDateInput />
</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>
<button (click)="resetInformation()">Clear</button>
And my TS code is:
@ViewChild('startDateInput', { static: false }) startDateInput?: ElementRef<HTMLInputElement>;
@ViewChild('endDateInput', { static: false }) endDateInput?: ElementRef<HTMLInputElement>;
range = new FormGroup({
start: new FormControl(null),
end: new FormControl(null),
});
resetInformation() {
this.startDateInput!.nativeElement.value = '';
this.endDateInput!.nativeElement.value = '';
this.range.reset();
}
I am using an Angular Materials Component, Datepicker
and when I try to clear the information (from the inputs), it doesn't clear the selection made in the calendar, as shown in the below picture:
Does anyone know how I can remove the selection?
CodePudding user response:
Use the forms
integration with your DatePicker
to be able to set or reset values.
Template :
<mat-form-field appearance="fill">
<mat-label>Enter a date range</mat-label>
<mat-date-range-input [rangePicker]="picker" [formGroup]="range">
<input matStartDate placeholder="Start date" formControlName="start" />
<input matEndDate placeholder="End date" formControlName="end" />
</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>
<button (click)="resetInformation()">Clear</button>
Main additions (vs your code) :
[formGroup]="range"
onmat-date-range-input
to be linked withFormGroup
defined inapp.component.ts
formControlName="start"
andformControlName="end"
added on eachinput
to be linked with each control of form group.
Component :
@Component({...})
export class AppComponent {
range = new FormGroup({
start: new FormControl<Date | null>(null),
end: new FormControl<Date | null>(null),
});
resetInformation() {
this.range.reset();
}
}
More details on official docs