How can I clear an Angular Material Datepicker with an button click?
I've tried .date .value .clear .reset .resetDate
None of them seem to clear the Datepicker.
HTML:
<mat-form-field>
<input matInput [matDatepicker]="fromDatePicker" placeholder="From Date" disabled>
<mat-datepicker-toggle matSuffix [for]="fromDatePicker"></mat-datepicker-toggle>
<mat-datepicker #fromDatePicker disabled="false"></mat-datepicker>
</mat-form-field>
<mat-form-field>
<input matInput [matDatepicker]="toDatePicker" placeholder="To Date" disabled>
<mat-datepicker-toggle matSuffix [for]="toDatePicker"></mat-datepicker-toggle>
<mat-datepicker #toDatePicker disabled="false"></mat-datepicker>
</mat-form-field>
<button mat-raised-button (click)="resetForm()">Reset</button>
Typescript:
@ViewChild('fromDatePicker') fromDate: any;
@ViewChild('toDatePicker') toDate: any;
resetForm() {
this.searchString.nativeElement.value = "";
this.fromDate.value = undefined;
this.fromDate.date = null;
this.toDate.date = undefined;
};
You must query for the matInput
element.
component.ts
@ViewChild('fromInput', {
read: MatInput
}) fromInput: MatInput;
@ViewChild('toInput', {
read: MatInput
}) toInput: MatInput;
resetForm() {
this.fromInput.value = '';
this.toInput.value = '';
}
component.html
<mat-form-field>
<input #fromInput matInput [matDatepicker]="fromDatePicker" placeholder="From Date" disabled>
<mat-datepicker-toggle matSuffix [for]="fromDatePicker"></mat-datepicker-toggle>
<mat-datepicker #fromDatePicker disabled="false"></mat-datepicker>
</mat-form-field>
<mat-form-field>
<input #toInput matInput [matDatepicker]="toDatePicker" placeholder="To Date" disabled>
<mat-datepicker-toggle matSuffix [for]="toDatePicker"></mat-datepicker-toggle>
<mat-datepicker #toDatePicker disabled="false"></mat-datepicker>
</mat-form-field>
<button mat-raised-button (click)="resetForm()">Reset</button>
Live demo
HTML
<mat-datepicker (opened)="resetPicker()" class="mat-datepicker" #picker></mat-datepicker>
TS
@ViewChild(MatDatepicker)
picker: MatDatepicker<Moment>;
resetPicker() {
this.picker.select(undefined);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With