11

How to detect language change in other components? My detection is made in header component. My target is to detect language change and set style.

Child component:

import { TranslateService } from "ng2-translate";
export class ChildComponent{
    public browserLang: string;
    constructor(private translate: TranslateService) {
        this.browserLang = translate.getBrowserLang();
    }
}

Html of child:

<div ng-class="{black: browserLang == 'en', red: browserLang == 'de'}" >

Result of that is: Class is not added. If I output language string (en) is proper. But it did not listen for any changes. How to make it listen and changing classes?

pbialy
  • 1,025
  • 14
  • 26
IntoTheDeep
  • 4,027
  • 15
  • 39
  • 84
  • this might help you http://mean.expert/2016/05/21/angular-2-component-communication/ using this method component can talk each other. – Vinay Pandya Feb 28 '17 at 11:52
  • other way is that you can create one service which sets some variable, like get set method. here get should return Observable so when you change variable, other component which has subscribed they detect the changes. – Vinay Pandya Feb 28 '17 at 11:56

1 Answers1

29

Adding those do the trick:

import {TranslateService, LangChangeEvent} from "ng2-translate"

export class ChildComponent {
    public browserLang: string;
    constructor(private translate: TranslateService) {
        translate.onLangChange.subscribe(lang=>{
            this.browserLang = lang;
        })
    }
    ngOnInit(){
        this.translate.onLangChange.subscribe((event: LangChangeEvent) => {
            this.browserLang = event.lang
        });
    }
}
IntoTheDeep
  • 4,027
  • 15
  • 39
  • 84