Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you get ngx-translate work with angular material

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<mat-select class="lang-selector__dropdown" [(ngModel)]="translate.use">
  <mat-option *ngFor="let lang of translate.getLangs()" [value]="translate.use">{{ lang | uppercase }}</mat-option>
</mat-select>

>Solution :

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 class="lang-selector__dropdown (selectionChange)="translate.use($event.value)">
  <mat-option *ngFor="let lang of translate.getLangs()" [value]="lang">{{ lang | uppercase }}</mat-option>
</mat-select>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading