Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular matDatepicker locale fail typing in input box

If I use a datepicker as in

<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>

and set a locale as in

  providers: [    
    { provide: LOCALE_ID, useValue: 'it-IT' },
    { provide: MAT_DATE_LOCALE, useValue: 'it-IT' }]

it works if the user select date from picker, but if he types inside the input box the date is not parsed in the right way. Eg: the Italian format is dd/mm/yyyy if the user select March 31th,2018 in the box we get "31/03/2018" (it's ok) but if he types "31/03/2018" the date is not validate (but it is a valid Italian date). If he types "03/05/2018" we get March, 5th instead of May 3rd. Is it a angular material bug or I made some mistakes?

I also tried 'it' in place of 'it-IT'.

like image 633
user2959635 Avatar asked Oct 15 '18 13:10

user2959635


1 Answers

According to the angular material example you can use this

import {Component} from '@angular/core';
import {MAT_MOMENT_DATE_FORMATS, MomentDateAdapter} from '@angular/material-moment-adapter';
import {DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from '@angular/material/core';

/** @title Datepicker with different locale */
@Component({
  selector: 'datepicker-locale-example',
  templateUrl: 'datepicker-locale-example.html',
  styleUrls: ['datepicker-locale-example.css'],
  providers: [
    // The locale would typically be provided on the root module of your application. We do it at
    // the component level here, due to limitations of our example generation script.
    {provide: MAT_DATE_LOCALE, useValue: 'ja-JP'},

    // `MomentDateAdapter` and `MAT_MOMENT_DATE_FORMATS` can be automatically provided by importing
    // `MatMomentDateModule` in your applications root module. We provide it at the component level
    // here, due to limitations of our example generation script.
    {provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE]},
    {provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS},
  ],
})

Make sure you npm install --save package @angular/material-moment-adapter or yarn add package @angular/material-moment-adapter

like image 51
Hopefulee Avatar answered Oct 19 '22 22:10

Hopefulee