Input date in Angular Material date picker in dd/MM/yyyyy format
I am trying to create an application that takes a date as user input which is then passed as a parameter to an API call. The local date format is dd/MM/yyyy. I want the user to be able to enter the date via the input OR the mat-datepicker
in the local format.
Standard syntax for reactive forms with material (mat-datepicker, matInput) etc looks like:
Template:
<mat-form-field>
<mat-label>Date of Birth:</mat-label>
<input matInput [matDatepicker]="dobPicker" formControlName="dobCtrl"
(click)="dobPicker.open()"/>
<mat-datepicker-toggle matSuffix [for]="dobPicker">
<mat-icon matDatepickerToggleIcon>calendar_month</mat-icon>
</mat-datepicker-toggle>
<mat-datepicker #dobPicker startView="multi-year">
</mat-datepicker>
</mat-form-field>`
Component constructor:
this.Form = new FormGroup({
agreeCtrl: new FormControl(''),
dobCtrl: new FormControl('')
});
It makes no difference if I insert {{ dob | date }}
between the mat-datepicker
tags
My angular.json has the following:
"projects": {
"project-name": {
"projectType": "application",
"i18n": {
"sourceLocale": "en-AU"
},
Currently, the user cannot type a date into the input box in dd/MM/yyyy format. It works if the user inputs a date in US (MM/dd/yyyy) format, but shows as invalid as soon as a number greater than 12 is input to the text box. If a date is selected via the datepicker it displays in the correct (dd/MM/yyyy) format and shows as valid, but if the user then changes (eg) the month, the date in the input becomes invalid.
I went down a bit of a rabbit hole with something called moment.js as it appeared to be a well-known solution, however moment has been deprecated (with the blessing of the moment devs), with date-fns listed as its replacements, so I don't want a moment solution.
What do I have to change to allow dd/MM/yyyy input via both the input and/or the mat-datepicker?
1 answer
You should just be able to alter the MAT_DATE_LOCALE
provider by adding something like { provide: MAT_DATE_LOCALE, useValue: 'en-AU' }
to your module's providers
array.
Angular Material's docs are pretty neat; take a look at this section regarding datepicker i18n.
0 comment threads