Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear mat-datepicker in Angular 5

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;

  };
like image 989
PrivateJoker Avatar asked Apr 23 '18 14:04

PrivateJoker


2 Answers

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

like image 82
Tomasz Kula Avatar answered Sep 17 '22 18:09

Tomasz Kula


HTML

  <mat-datepicker (opened)="resetPicker()" class="mat-datepicker" #picker></mat-datepicker>

TS

  @ViewChild(MatDatepicker)
  picker: MatDatepicker<Moment>;
  resetPicker() {
    this.picker.select(undefined);
  }
like image 38
rivanov Avatar answered Sep 18 '22 18:09

rivanov