Reputation: 133
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?
Upvotes: 7
Views: 12026
Reputation: 9
It always uses the default language. This is the main problem. The solution is:
this.translateService.onLangChange.subscribe((event: TranslationChangeEvent) => {
this.translateService.setDefaultLang(event.lang);
});
Upvotes: 0
Reputation: 844
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
Upvotes: 9