h2qutc / angular-material-components

Angular Material Library provide extra components for every project
https://h2qutc.github.io/angular-material-components/
MIT License
330 stars 156 forks source link

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

Open devAnky opened 2 years ago

devAnky commented 2 years ago

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');
    }
andrewiankidd commented 1 year ago

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();
    }
}