Angular 2 TranslateService detect language change

IntoTheDeep picture IntoTheDeep · Feb 28, 2017 · Viewed 7.9k times · Source

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?

Answer

IntoTheDeep picture IntoTheDeep · Feb 28, 2017

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
        });
    }
}