Muhammad Ali
Muhammad Ali

Reputation: 369

Angular 6 language translation does not change unless page refresh

I have 5 different languages and default is english. In my header I switch languages

header.component.ts

  onSetLanguage(lang: string) {
    this.trans.use(lang);
    this.currentLang = localStorage.setItem("currentLang", lang);
  }

and in my app.component.ts

  constructor(
    private authService: AuthService,
    private translate: TranslateService
  ) {
    this.translate.setDefaultLang("en");
    const currentLang = localStorage.getItem("currentLang");
    if (currentLang !== null) {
      this.translate.use(currentLang);
    } else {
      this.translate.use("en");
    }
  }

the problem is when I log in first time it returns null on the current language. Then I select some language for example german it returns (de) which is fine.

when I submit the form and before pressing the submit i change it to Italian (it) it will still submit (de) to the form (even though the translations on the UI are changed) until i refresh the page or go back to previous component and get back to form component again.

How do I fix it?

Upvotes: 0

Views: 1259

Answers (1)

Mohsin Ayaz
Mohsin Ayaz

Reputation: 11

You put all the functionality in app component constructor. when application loads the first thing run is constructor that why it show null. create a service in which move your functionality and use it in app.component

Upvotes: 1

Related Questions