1. Create a class that extends NativeDateAdapter
import { NativeDateAdapter, DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE } from '@angular/material/core';
import { formatDate } from '@angular/common';
export const MY_FORMATS = {
parse: {
dateInput: 'yyyy-MM-dd', // date format used by the text field
},
display: {
dateInput: 'yyyy-MM-dd', // date format used by the text field
monthYearLabel: 'MMM-YYYY', // the date on the top left of the date picker
dateA11yLabel: 'LL',
monthYearA11yLabel: 'MM-yyyy',
}
};
export class MyDateAdaper extends NativeDateAdapter {
override format(date: Date, displayFormat: Object): string {
return formatDate(date, displayFormat+'', this.locale);
}
}
2. In your component class, specify we are using MyDateAdapter in @Component.
import { Component, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormControl } from '@angular/forms';
import { Case } from '../case/case';
import { CaseAct } from '../case/caseAct';
import { CaseAsmt } from '../case/caseAsmt';
import { StatOrdSummary } from '../case/statOrdSummary';
import { SelectItem } from '../case/selectItem';
import { Observable, Subject, interval, of, mergeMap, concatMap, switchMap } from 'rxjs';
import { HeroService } from '../service/hero.service';
import { FactoryService } from '../service/factory.service';
import { debounceTime, distinctUntilChanged, filter, map, scan, reduce, tap } from 'rxjs/operators';
import { MatTabGroup } from '@angular/material/tabs';
import { MatSnackBar } from '@angular/material/snack-bar';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatRadioModule } from '@angular/material/radio';
import { MatDialog, MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { CommonDialogComponent } from '../dialog/common-dialog/common-dialog.component';
import { DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE } from '@angular/material/core';
import { MyDateAdaper, MY_FORMATS } from '../common/myDateFormat';
import { TRANSLOCO_SCOPE } from '@ngneat/transloco';
@Component({
selector: 'app-case',
templateUrl: './case.component.html',
styleUrls: ['./case.component.css'],
providers: [
{
provide: DateAdapter,
useClass: MyDateAdaper,
},
{
provide: MAT_DATE_FORMATS,
useValue: MY_FORMATS
},
],
})
export class CaseComponent implements OnInit {
.....
}
3. In html template, nothing to config for the date format.
<mat-form-field appearance="fill" class="form-field ">
<mat-label>Iss Dt</mat-label>
<input matInput [matDatepicker]="picker" [(ngModel)]="a.ordrIsuDt" />
<mat-hint>YYYY-MM-DD</mat-hint>
<mat-datepicker-toggle matIconSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>