How to update mat-datepicker language dynamically in standalone components?

Discussão em 'Angular' iniciado por AstroCoder, Janeiro 24, 2025.

  1. AstroCoder

    AstroCoder Guest

    I need to translate all my mat-datepickers globally and dynamically. All my components are standalone and I have a tool to which languages. When I import this directive to each component it works but I want a solution where I don't have to add this directive to each standalone component. I'm using Angular-18.

    date-local.directive.ts

    @Directive({
    selector: '[matDatepicker]',
    standalone: true,
    })
    export class DateLocaleDirective implements OnDestroy
    {
    constructor(private dateAdapter: DateAdapter<Date>, private translateService: TranslateService)
    {
    this.dateAdapter.setLocale(this.translateService.currentLang);
    this.translateService.onLangChange.subscribe((event: LangChangeEvent) =>
    {
    console.log("event.lang", event.lang);
    this.dateAdapter.setLocale(event.lang);
    });
    }
    }


    Importing my custom directive to a standalone component (works this way but i don't want this solution)

    @Component({
    selector: 'app-home-page',
    standalone: true,
    imports: [
    DateLocaleDirective
    ],
    templateUrl: './home.component.html'
    })


    Can all mat-datepickers be updated at root/globally?

    Continue reading...

Compartilhe esta Página