Angular 5从组件更新指令

时间:2018-01-19 21:26:44

标签: angular

我正在尝试为按钮进行翻译,所以当我从下拉列表中选择语言时,我想使用指令更改按钮文本。以下是各自的代码。 home.component.ts

this._i18nDirective.i18nLanguage包含Object Key,我将从JSON语言中选择。

export class HomeComponent implements OnInit {

    appSelectLanguages: any = [];
    selectedAppLangaugeValue = '';
    @ViewChild(I18nDirective) _i18nDirective;
    constructor() { }

    ngOnInit = () => {
    }

    appLanguageChange__Event = () => {
        this._i18nDirective.setterMultiParams(this._i18nDirective._el.nativeElement, this._i18nDirective.i18nLanguage);
    }
}`

i18ndirectve:

`import { Directive, ElementRef, HostListener, Input, Renderer, ViewContainerRef } from '@angular/core';
import { NGXLogger } from 'ngx-logger';
import * as _ from 'underscore';
import { ConfigService } from '../providers/config.service';
import { HttpService } from '../providers/http.service';

@Directive({
  selector: '[appI18n]'
})
export class I18nDirective {

    private i18nLanguage: any = {};

    constructor(
        private _ConfigService: ConfigService,
        private _Logger: NGXLogger,
        private _el: ElementRef,
        private _Renderer: Renderer,
        private _HttpService: HttpService
    ) {
        this._ConfigService.appLanguageEvent.subscribe(value => {this.i18nLanguage = value; this._Logger.debug(value); });
     }

    @Input() set appI18n (_key: string) {
        if (this.i18nLanguage && this.i18nLanguage.data) {
            this.setter(_key);
        }
        else {
            this._HttpService.languageGetter(this._ConfigService.defaultLanguage).subscribe(response => {
                const appLangData: any = {};
                appLangData.data = response;
                appLangData.action = 'SET_APP_LANGUAGE';
                this._ConfigService.setter(appLangData);
                setTimeout(() => {
                    this.setter(_key);
                }, 1000);
            });
        }
    }

    setter = (_key) => {
        if (this.i18nLanguage.hasOwnProperty(_key)) {
            this._Renderer.setElementProperty(this._el.nativeElement, 'innerHTML', this.i18nLanguage[_key]);
        }
    }

    setterMultiParams = (_element, _key) => {
        const _keyName = Object.keys(_key);
        if (this.i18nLanguage.hasOwnProperty(_keyName)) {
            this._Renderer.setElementProperty(_element, 'innerHTML', this.i18nLanguage[_keyName[0]]);
        }
    }

}`

因此调用setterMultiParams方法来更新指令。问题是: 当我选择西班牙语时它仍然显示我的英文版本但是当我再次从下拉列表中选择英语时,我得到了我之前选择的西班牙语版本。它没有立即更新。

这是按钮:

<button mat-raised-button color="primary" class="_rx_fat_button _rx_footer_single_btn" appButtonAction [appButtonActionLabel]="'GET_STARTED'"><span [appI18n]="'GET_STARTED'"></span></button>

enter image description here

1 个答案:

答案 0 :(得分:0)

问题是我的ConfigService中的语言对象没有更新,这导致加载了负载json。这是我的错误

在拨打

之前添加延迟250毫秒
this._i18nDirective.setterMultiParams(this._i18nDirective._el.nativeElement, this._i18nDirective.i18nLanguage);

它按预期工作