0
votes

I try to use internationalization in my angular 9 application, when I open datepicker field it shows me the following error in console:

Console error screenshot

This is my DatePicker Adapter Code

import { Injectable } from '@angular/core';
import { NativeDateAdapter } from '@angular/material';
import { BehaviorSubject } from 'rxjs';


export const CUSTOM_DATE_FORMAT = {
    parse: {
        dateInput: null
    },
    display: {
        dateInput: 'CustomFormat',
        monthYearLabel: { year: 'numeric', month: 'short' },
        dateA11yLabel: { year: 'numeric', month: 'long', day: 'numeric' },
        monthYearA11yLabel: { year: 'numeric', month: 'long' },
    }
};

export const datepicker: BehaviorSubject<string> = new BehaviorSubject('');

@Injectable()
export class Datepicker extends NativeDateAdapter {


    private subscription: any;

    format(date: Date, displayFormat?: string | object): string {
        if (!this.subscription) {
            this.subscription = datepicker.subscribe(v => {
                this.setLocale(v);
            });
        }

        if (this.locale === 'CustomFormat') {
            const day = date.getUTCDate();
            const month = date.getUTCMonth() + 1;
            const year = date.getFullYear();

            // Return the format as per your requirement
            return `${day}.${month}.${year}`;
        } else {
            // Refer to the standard formatting of the NativeDateAdapter.
            return super.format(date, displayFormat);
        }
    }

}
1

1 Answers

0
votes

If you call setLocale format func gets called again because of a change trigger inside so you would never get out of this, which is resulting in call stack size exceeded.

Change format function to:

format(date: Date, displayFormat?: string | Object): string {
    let loc = appLocale.getValue();
    if (this.locale !== loc)
        this.setLocale(loc);
    return super.format(date, displayFormat);
}

If you subscribe to an BehaviorSubject you will get a lot of change calls even if it is the same value.

You can check this one