I have created an angular material date picker component to use with formly
, and tried to set it to use GB for the locale so that dates are shown as 26/07/2019
. However, when typing in the date, it parses as US still, resulting in invalid date errors being shown.
I have tried to include moment
and the MomentDateAdapter
module but have been unable to solve the issue.
Here is a stackblitz
I've set my providers like so:
providers: [
{ provide: LOCALE_ID, useValue: 'en-GB' },
{ provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] },
{ provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS },
]
and my component looks like this:
import { Component, ViewChild } from '@angular/core';
import { FormControl } from '@angular/forms';
import { FieldType } from '@ngx-formly/material';
import { MatInput } from '@angular/material';
import * as _moment from 'moment';
// tslint:disable-next-line:no-duplicate-imports
import {default as _rollupMoment} from 'moment';
const moment = _rollupMoment || _moment;
@Component({
selector: 'app-form-datepicker-type',
template: `
<input matInput
[errorStateMatcher]="errorStateMatcher"
[formControl]="formControl"
[matDatepicker]="picker"
[matDatepickerFilter]="to.datepickerOptions.filter"
[formlyAttributes]="field">
<ng-template #matSuffix>
<mat-datepicker-toggle [for]="picker"></mat-datepicker-toggle>
</ng-template>
<mat-datepicker #picker></mat-datepicker>
`,
})
export class DatepickerTypeComponent extends FieldType {
// Datepicker takes `Moment` objects instead of `Date` objects.
date = new FormControl(moment([2017, 0, 1]));
}