robisim74 / angular-l10n

Angular library to translate texts, dates and numbers
MIT License
380 stars 59 forks source link

How to Overwrite PARSE_DATE_STYLE #314

Closed SchneMa closed 4 years ago

SchneMa commented 4 years ago

I just wanted to extend the short date format to use 2 digital values for month and day with leading zeros but I'm unable to overwrite the PARSE_DATE_STYLE constant. I tryed it by passing a custom provider to platformBrowserDynamicbut it seems to be overwritten somewhere else.

Am I missing something or shouldn't this be the way to overwrite the default value.

Thanks in advance!


const customAngularL10nDateParseStyle: { [format: string]: any; } = {
    full: { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' },
    long: { year: 'numeric', month: 'long', day: 'numeric' },
    medium: { year: 'numeric', month: 'short', day: 'numeric' },
    short: { year: 'numeric', month: '2-digit', day: '2-digit' }
}

const providers: StaticProvider[] = [
    { provide: LOCALE_ID, useValue: 'de-DE' },
    { provide: PARSE_DATE_STYLE, useValue: customAngularL10nDateParseStyle }
];

platformBrowserDynamic(providers).bootstrapModule(AppModule).catch(err => console.error(err));
robisim74 commented 4 years ago

Hi @SchneMa,

PARSE_DATE_STYLE is not an injection token, so you cannot override it through dependency injection.

The simplest way is to build your custom options, e.g.:

    shortDateOptions: L10nDateTimeFormatOptions = {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
    };

and pass them to pipes/directives:

<p>{{ today | l10nDate:locale.language:shortDateOptions }}</p>

If you prefer, you can also put them in an injection token and pass them to the components that use them.

SchneMa commented 4 years ago

Thank you for your help!

Works like a charm!