HTML code
<mat-form-field>
<input matInput placeholder=”Select Date” [matDatepicker]=”datepickerRef” name=”datepicker” ngModel #dateCtrl=”ngModel” required readonly/>
<mat-datepicker-toggle [for]=”datepickerRef” matSuffix></mat-datepicker-toggle>
<mat-datepicker #datepickerRef></mat-datepicker>
<mat-error *ngIf=”dateCtrl.errors?.required && deptCtrl.touched”>Choose a Date</mat-error>
</mat-form-field>
This is the helper function write on file name format-datepicker.ts
import { NativeDateAdapter } from ‘@angular/material’;
import { MatDateFormats } from ‘@angular/material/core’;
export class AppDateAdapter extends NativeDateAdapter {
format(date: Date, displayFormat: Object): string {
if (displayFormat === ‘input’) {
let day: string = date.getDate().toString();
day = +day < 10 ? ‘0’ + day : day;
let month: string = (date.getMonth() + 1).toString();
month = +month < 10 ? ‘0’ + month : month;
let year = date.getFullYear();
return `${day}-${month}-${year}`;
}
return date.toDateString();
}
}
export const APP_DATE_FORMATS: MatDateFormats = {
parse: {
dateInput: { month: ‘short’, year: ‘numeric’, day: ‘numeric’ },
},
display: {
dateInput: ‘input’,
monthYearLabel: { year: ‘numeric’, month: ‘numeric’ },
dateA11yLabel: { year: ‘numeric’, month: ‘long’, day: ‘numeric’
},
monthYearA11yLabel: { year: ‘numeric’, month: ‘long’ },
}
};
Provide above implementation inside the providers tag.
import {DateAdapter, MAT_DATE_FORMATS} from '@angular/material/core';
import { AppDateAdapter, APP_DATE_FORMATS } from 'src/app/shared/format-datepicker';
@Component({
providers: [
{provide: DateAdapter, useClass: AppDateAdapter},
{provide: MAT_DATE_FORMATS, useValue: APP_DATE_FORMATS}
]
})
I tried this out by using this article
https://amandeepkochhar.medium.com/angular-material-datepicker-set-custom-date-in-dd-mm-yyyy-format-5c0f4340e57
and it works!!