Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngx-translate issue with translate instant

I am using ngx-translate in Angular(v6) with lazy-loading approach. I am facing a problem with translate.instant('Title')

Using translate pipe it works fine.( {{'Title' | translate}})

Using translate.instant() method the default language always works, but I am unable to change language via language selector(select component used for switching language) which is in shared module.

I don't want to use this.translate.onLangChange.subscribe each time, is there an alternative to using this method?

like image 976
Roshin Thomas Avatar asked Mar 28 '19 15:03

Roshin Thomas


People also ask

How does Ngx-translate work?

What is ngx-translate? ngx-translate is the library for internationalization (i18n) and localization in Angular. It simplifies your Angular application to work for localization. It's easy to set up and use in an Angular application.

What is NGX-translate http loader?

The @ngx-translate/http-loader loads the translation files from your webserver. The HttpLoaderFactory is required for AOT (ahead of time) compilation in your project. First, you have to inject TranslateService in the constructor. The next step is to set the default language of your application using translate.

What is angular translate?

What? angular-translate is an AngularJS module that makes your life much easier when it comes to i18n and l10n including lazy loading and pluralization.


1 Answers

Use translate.stream('Title') instead of translate.instant('Title'). It returns an Observable.

See also https://github.com/ngx-translate/core

How it works:

import {Component} from '@angular/core';
import {TranslateService} from '@ngx-translate/core';
import {Observable} from 'rxjs';

@Component({
  selector: 'app-root',
  template: `
    <div>
      <h2>{{ 'HOME.TITLE' | translate }}</h2>
      <label>
        {{ 'HOME.SELECT' | translate }}
        <select #langSelect (change)="translate.use(langSelect.value)">
          <option *ngFor="let lang of translate.getLangs()" [value]="lang" [selected]="lang === translate.currentLang">{{ lang }}</option>
        </select>
      </label>
      <ng-container *ngIf="name$ | async as name">
        <p>Observable {{ name }}</p>
      </ng-container>
    </div>
  `,
})
export class AppComponent {
  public name$: Observable<string>;

  constructor(public translate: TranslateService) {
    translate.addLangs(['en', 'fr']);
    translate.setDefaultLang('en');

    const browserLang = translate.getBrowserLang();
    translate.use(browserLang.match(/en|fr/) ? browserLang : 'en');
  }

  public ngOnInit(): void {
    this.name$ = this.translate.stream('HOME.TITLE');
  }
}

Here is a link to a stackblitz demo: https://stackblitz.com/edit/github-az4kgy

like image 60
Pierre Avatar answered Oct 10 '22 01:10

Pierre