Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 976
IntoTheDeep Avatar asked Feb 28 '17 11:02

IntoTheDeep


People also ask

How does Ngx translator work?

NGX-Translate is an internationalization library for Angular. Internationalization is the process of translating an application into multiple languages. Using this library, we can translate our application language into multiple languages. This will work with not only static data, but dynamic data as well.

What is translate pipe in angular?

The service also contains a method called translate. It is later called by the pipe to get the translation for a specific key. It always uses the language specified in the 'language'-variable of the service, to lookup the translation. That's it.


1 Answers

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
        });
    }
}
like image 168
IntoTheDeep Avatar answered Oct 21 '22 09:10

IntoTheDeep