'Datepicker Angular Material: Input field format change when change value of the field
I'm using a mat-date-rang-input of Angular Material. I changed the date format of Angular Material from MM/dd/yyyy to dd/MM/yyyy, and that's works alright.
<mat-form-field ngClass="filters_dateInterval">
<mat-label>Date interval</mat-label>
<mat-date-range-input [rangePicker]="picker" md-date-locale="{
inputDisplay: dd/MM/yyyy
}}">
<input matStartDate placeholder="Início" [(ngModel)]="dateStartFilterField" (valueChanges)="show($event)" />
<input matEndDate placeholder="Fim" [(ngModel)]="dateEndFilterField" />
</mat-date-range-input>
<mat-datepicker-toggle matSuffix [for]="picker" ngClass="filters_dateInterval__icon"></mat-datepicker-toggle>
<mat-date-range-picker #picker></mat-date-range-picker>
</mat-form-field>
However, when I tested the ui/ux, I noticed something unusual. After I wrote a date in the format dd/MM/yyyy and focused out, it lost that format and the date changed to the format MM/dd/yyyy.
I tried changing the app.module.ts to include a provider to format the date.
providers: [
{
provide: LOCALE_ID,
useValue: DATE_FORMAT_PTBR
}
]
This is my DATE_FORMAT_PTBR:
export const DATE_FORMAT_PTBR = {
parse: {
dateInput: 'dd/MM/yyyy',
},
display: {
dateInput: 'dd/MM/yyyy',
monthYearLabel: 'MMMM YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'MMMM YYYY'
},
formater: {
dateInput: 'dd/MM/yyyy',
}
};
I tried changing the useValue of providers to 'pt-BR' too, but it did not affect the situation.
Solution 1:[1]
Correct the TS file as below,
import { MAT_DATE_FORMATS } from '@angular/material/core';
export const MY_DATE_FORMATS = {
parse: {
dateInput: 'DD/MM/YYYY',
},
display: {
dateInput: 'DD/MM/YYYY',
monthYearLabel: 'MMMM YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'MMMM YYYY'
},
};
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [
{ provide: MAT_DATE_FORMATS, useValue: MY_DATE_FORMATS }
]
})
And HTML file as below,
<mat-form-field>
<input matInput [matDatepicker]="picker" placeholder="Choose a date">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker ></mat-datepicker>
</mat-form-field>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | turivishal |
