Angular 2 TranslateService检测语言更改

时间:2017-02-28 11:47:32

标签: javascript html angular angular-translate

如何检测其他组件中的语言更改?我的检测是在标题组件中进行的。我的目标是检测语言变化并设置风格。

子组件:

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

孩子的HTML:

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

结果是:未添加类。如果我输出语言字符串(en)是正确的。但它没有听取任何改变。如何让它听和改变课程?

1 个答案:

答案 0 :(得分:3)

添加这些可以解决问题:

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