angular-material-components icon indicating copy to clipboard operation
angular-material-components copied to clipboard

ngxMatDatetimePicker : Setting locale results in not being able to fill the field manually

Open devAnky opened this issue 2 years ago • 1 comments

If I set the locale on the NgxMatDateAdapter via setLocale to de-DE or fr-FR (did not test more locales), the user is not able to manually input or change the date and time. The field gets rendered in error state instead and the form control returns null value. And the value in the popup is still the value before the manual change. Am I doing something wrong? We are using Angular 14.0.1 and datetime-picker 8.0.0

image image

code to set locale:

 constructor(...
                private adapter: NgxMatDateAdapter<Date>) {
        adapter.setLocale('fr-FR');
    }

devAnky avatar Jul 27 '22 11:07 devAnky

You can work around this by using a CustomDateAdapter that implements format and parse

example.module.ts


const materialModules = [
	MatNativeDateModule,
	NgxMatDatetimePickerModule,
	NgxMatTimepickerModule,
	NgxMatNativeDateModule
]

export const MOMENT_DATETIME_WITH_SECONDS_FORMAT = 'DD/MM/yyyy HH:mm:ss';
const CUSTOM_MOMENT_FORMATS: NgxMatDateFormats = {
	parse: {
		dateInput: MOMENT_DATETIME_WITH_SECONDS_FORMAT,
	},
	display: {
		dateInput: MOMENT_DATETIME_WITH_SECONDS_FORMAT,
		monthYearLabel: 'MMM YYYY',
		dateA11yLabel: 'LL',
		monthYearA11yLabel: 'MMMM YYYY',
	},
};

@NgModule({
	imports: [
		CommonModule,
		...materialModules
	],
	exports: [
		...materialModules
	],
	providers: [
		{
			provide: NGX_MAT_DATE_FORMATS,
			useValue: CUSTOM_MOMENT_FORMATS
		},
		{
			provide: MAT_DATE_FORMATS,
			useValue: CUSTOM_MOMENT_FORMATS
		},
		{
			provide: MAT_DATE_LOCALE,
			useValue: 'en-GB'
		},
		{
			provide: NGX_MAT_MOMENT_DATE_ADAPTER_OPTIONS,
			useValue: {useUtc: true}
		},
		{
			provide: NGX_MAT_MOMENT_DATE_ADAPTER_OPTIONS,
			useValue: {useUtc: true}
		},
		{
			provide: NgxMatDateAdapter,
			useClass: CustomDateAdapter
		}
	]
})

customDate.adapter.ts

import { NgxMatNativeDateAdapter } from '@angular-material-components/datetime-picker';
import * as moment from 'moment';
import { MOMENT_DATETIME_WITH_SECONDS_FORMAT } from 'example.module';

export class CustomDateAdapter extends NgxMatNativeDateAdapter {

	format(date: Date, displayFormat: Object): string {
		return moment(date).format(displayFormat.toString());       
	}

	parse(value: any): Date {
		return moment(value, MOMENT_DATETIME_WITH_SECONDS_FORMAT).toDate();
	}
}

andrewiankidd avatar Mar 05 '23 14:03 andrewiankidd