Angular Material mat-datepicker (change) event and format
HTML:
<div class="someClass">
<mat-form-field appearance="outline">
<mat-label>Label</mat-label>
<input (dateChange)="onDateChange($event)" formControlName="formControlName" matInput [matDatepicker]="picker">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>
</div>
TS:
public onDateChange(event: MatDatepickerInputEvent<Date>): void {
console.log('Teste', event.value);
}
In your html you can use (ngModelChange)="functionName()" to trigger any function with the change of the date and declare the function in your ts.
To change the format of the date :
Add this to app.module.ts
:
import{MatDateFormats, MAT_DATE_FORMATS, NativeDateAdapter, DateAdapter} from '@angular/material';
const MY_DATE_FORMATS = {
parse: {
dateInput: { day: 'numeric', month: 'numeric', year: 'numeric' }
},
display: {
dateInput: 'input',
monthYearLabel: { year: 'numeric', month: 'short' },
dateA11yLabel: { year: 'numeric', month: 'long', day: 'numeric' },
monthYearA11yLabel: { year: 'numeric', month: 'long' },
}
};
export class AppDateAdapter extends NativeDateAdapter {
format(date: Date, displayFormat: Object): string {
if (displayFormat === 'input') {
const day = date.getDate();
const month = date.getMonth() + 1;
const year = date.getFullYear();
return `${day}/${month}/${year}`;
} else {
return date.toDateString();
}
}
}
Add the below in providers of app.module.ts
:
{provide: DateAdapter, useClass: AppDateAdapter},
{provide: MAT_DATE_FORMATS, useValue: MY_DATE_FORMATS}
from docs you can use one of the below events based on your requirement
@Output()
dateChange(): EventEmitter<MatDatepickerInputEvent<D>>
Emits when a change event is fired on this .
@Output()
dateInput(): EventEmitter<MatDatepickerInputEvent<D>>
Emits when an input event is fired on this .
For example:
<input matInput #ref [matDatepicker]="organizationValue" formControlName="organizationValue" (dateChange)="orgValueChange(ref.value)">
or
<input matInput #ref [matDatepicker]="organizationValue" formControlName="organizationValue" (dateInput)="orgValueChange(ref.value)">
Here is what I did, Angular 9 :
html:
<input
matInput
[matDatepicker]="picker"
(dateChange)="onDateChange()"
/>
ts:
@Output()
dateChange: EventEmitter<MatDatepickerInputEvent<any>> = new EventEmitter();
onDateChange(): void {
this.dateChange.emit();
}