Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a clear button in `mat-datepicker`

How to add a clear button in mat-datepicker. Exactly in the open calendar how to add a date cleaning button.

<input matInput [(ngModel)]="data1" [matDatepicker]="data1" [value]="" formControlName="data1" id="data1" name="data1">
<mat-datepicker-toggle matSuffix [for]="data1"></mat-datepicker-toggle>
<mat-datepicker #data1></mat-datepicker>

I put inside the attribute:

<input matInput [(ngModel)]="data1" [matDatepicker]="data1" [value]="" formControlName="data1" id="data1" name="data1">
<mat-datepicker-toggle matSuffix [for]="data1"></mat-datepicker-toggle>
<mat-datepicker #data1>
    <button (click)="onClickMe()">
        <mat-icon matDatepickerToggleIcon>clear</mat-icon>
    </button>
</mat-datepicker>

but it doesn't work.

I would ask for help. Thank you.

like image 663
609tom Avatar asked Aug 13 '19 15:08

609tom


1 Answers

This solution uses the existing functionality of mat-datepicker-toggle without tying it to the datePicker using the for binding, which makes it do nothing instead of toggling the visibility of the calendar.

Adding a click binding allows arbitrary code to execute, in this case, calling the clear function in the component's JS/TS.

The icon on mat-datepicker-toggle can be customized by adding a child mat-icon component with a matDatepickerToggleIcon directive. This replaces the calendar icon with an arbitrary icon, in this case, the clear icon. source

By default, the icons are stacked vertically. This is fixed by making mat-datepicker-toggle display as inline-block with CSS.

Screenshot of the control

HTML

<mat-form-field appearance="fill">
    <mat-label>Start date</mat-label>
    <input matInput [matDatepicker]="startDatePicker" [(ngModel)]="startDate">
    <mat-datepicker-toggle matSuffix [for]="startDatePicker"></mat-datepicker-toggle>
    <mat-datepicker-toggle matSuffix (click)="clearStartDate()">
        <mat-icon matDatepickerToggleIcon>clear</mat-icon>
    </mat-datepicker-toggle>
    <mat-datepicker #startDatePicker></mat-datepicker>
</mat-form-field>

Component.ts

startDate: Date;

clearStartDate() {
    this.startDate = null;
}

CSS

mat-datepicker-toggle {
    display: inline-block;
}
like image 119
Ed54 Avatar answered Sep 28 '22 11:09

Ed54