IntoTheDeep
IntoTheDeep

Reputation: 4118

Angular 2 TranslateService detect language change

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?

Upvotes: 11

Views: 16059

Answers (1)

IntoTheDeep
IntoTheDeep

Reputation: 4118

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

Upvotes: 29

Related Questions