Home > Software design >  Angular: how to use ngx-translate in root component?
Angular: how to use ngx-translate in root component?

Time:07-29

I want to set global setting for ng-select, the "notFoundText" as translated value by ngx-translate TranslateService:

export class AppComponent {
  constructor(
    public translate: TranslateService,
    private readonly ngSelectConfig: NgSelectConfig
  ) {
    translate.addLangs(['pl-PL']);
    translate.setDefaultLang('pl-PL');

    this.ngSelectConfig.notFoundText =
      this.translate.instant('GENERAL.NO_DATA');
  }
}

In this implementation, translate.instant() returns "GENERAL.NO_DATA" instead of translated text. It works in several places (also in several modules, so generally my configuration works), but it does not work in root component. 'GENERAL.NO_DATA' also exists in my JSON file, because i'm using it for a long time.

How can I use TranslateService in this component?

CodePudding user response:

It got this problem when i work with ngx-translate first time. When app-component is inited, translate service hasn't finished the configuration yet so when you get translate text by instant method, it doesn't work and the result will be GENERAL.NO_DATA.

Solution: You should use get method

this.translate.get('GENERAL.NO_DATA').pipe(
take(1)
).subscribe(text => this.ngSelectConfig.notFoundText = text);
  • Related