By using a transloco language service changing the month abbreviations in the angular date picker

72 Views Asked by At

As you can see here I defined a format for my date picker

export const MY_FORMATS = {
  parse: {
    dateInput: "DD/MM/YYYY",
  },
  display: {
    dateInput: "DD/MM/YYYY",
    monthYearLabel: "DD/MMM YYYY",
    dateA11yLabel: "LL",
  },
};

I tried adding language code from outside to this

providers: [
    {
      provide: DateAdapter,
      useClass: MomentDateAdapter,
      deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS],
    },
    { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS },

To add language code from outside I changed useValue to useFactory and I sent the language code which returns from my language service, however since MY_FORMATS does not changed after program started it didnt work

In ngOnInit I take selected language code via this service

this.translocoService.langChanges$.subscribe((res) => { this.langCode = res;}

Below you can see what I have tried, I tried sendin langCode to moment.monthsShort() method to convert month names but didnt work

@Injectable({ providedIn: 'root' })
export class MyFormatsFactory {
  constructor(private translocoService: TranslocoService) {}

  createFormats() {
    const langCode = this.translocoService.getActiveLang();
    return createMyFormats(langCode);
  }
}

export const createMyFormats  = (langCode: string) => ({
  parse: {
    dateInput: "DD/MM/YYYY",
  },
  display: {
    dateInput: "DD/MM/YYYY",
    monthYearLabel: "DD/MMM YYYY",
    dateA11yLabel: "LL",
  },
  monthNames: moment.monthsShort(langCode), // language code for month names
});
@Component({
  selector: "app-home",
  templateUrl: "./home.component.html",
  styleUrls: ["./home.component.scss"],
  providers: [
    { provide: MAT_DATE_FORMATS, useFactory: (myFormatsFactory: MyFormatsFactory) => myFormatsFactory.createFormats() },
  ],
})
export class HomeComponent implements OnInit {
  languageCode: string; //variable to store language code
...
  }

  ngOnInit(): void {
    let myFormats = this.myFormatsFactory.createFormats();
...
}
0

There are 0 best solutions below