I'm a novice at Angular and have an angular app 13.3.6 with angular material 13.3.6 and ngx-translate 14.0.0. I use mat-option to select my languages, however when I click them, they don't change the website's language.
My translationservice looks like this:
export class TranslatorService implements OnInit {
constructor(public translate: TranslateService, private http: HttpClient) {
translate.addLangs(['nl', 'fr', 'en']);
translate.setDefaultLang('nl');
const browserLang: any = translate.getBrowserLang();
translate.use(browserLang.match(/nl|fr|en/) ? browserLang : 'nl');
}
// eslint-disable-next-line @angular-eslint/contextual-lifecycle
ngOnInit(): void {
this.translate.addLangs(['nl', 'fr', 'en']);
this.translate.setDefaultLang('nl');
const browserLang: any = this.translate.getBrowserLang();
this.translate.use(browserLang.match(/nl|fr|en/) ? browserLang : 'nl');
}
}
and my implementation in the component like this:
<mat-select [(ngModel)]="translate.use">
<mat-option *ngFor="let lang of translate.getLangs()" [value]="translate.use">{{ lang | uppercase }}</mat-option>
</mat-select>
CodePudding user response:
First issue with your code is that you are setting the value
of each option to a static function translate.use
, that cannot work. Instead, you want to set the value to the language, so you can work with it when the option gets selected.
Second issue is, that you are setting the [(ngModel)]
of the select to translate.use
. I have no clue what this does, but it definitely doesn't change the language. Instead, you can listen to the selectionChange
event and call translate.use()
in case it is fired.
Final code:
<mat-select translate.use($event.value)">
<mat-option *ngFor="let lang of translate.getLangs()" [value]="lang">{{ lang | uppercase }}</mat-option>
</mat-select>