ngx-translate翻译模块的所有子组件

时间:2019-05-15 02:55:54

标签: angular ngx-translate

我目前在Angular 7上使用ngx-translate。我的项目正在翻译两种语言,英语和中文,该项目由如下所示的结构组成,A.component是父组件,B.component是儿童组件。

模块A

    {
      componentB:{
         B.component.ts
         ....
      },
      A.component.ts
      A.module.ts
      .... 
    }

导出类BComponent实现OnInit {

  constructor(private translate: TranslateService
              ) {
        translate.addLangs(['zh-CN', 'en']);
        translate.use('zh-CN');
  }
}

上面的代码正在翻译。

但是如果上述代码仅添加到A.component而不添加到B.component。翻译不会在B.component上进行。

我想知道是否可以将代码添加到模块的父组件中,并且以下所有子组件可以自动转换而无需将代码放入每个子组件中。

2 个答案:

答案 0 :(得分:0)

我认为您应该像文档所述那样注入app.component.ts

  1. 首先导入TranslateModule:
import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {TranslateModule} from '@ngx-translate/core';

@NgModule({
    imports: [
        BrowserModule,
        TranslateModule.forRoot()
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }
  1. 为您的应用程序初始化TranslateService:
import {Component} from '@angular/core';
import {TranslateService} from '@ngx-translate/core';

@Component({
    selector: 'app',
    template: `
        <div>{{ 'HELLO' | translate:param }}</div>
    `
})
export class AppComponent {
    param = {value: 'world'};

    constructor(translate: TranslateService) {
        // this language will be used as a fallback when a translation isn't found in the current language
        translate.setDefaultLang('en');

         // the lang to use, if the lang isn't available, it will use the current loader to get them
        translate.use('en');
    }
}

答案 1 :(得分:0)

根据您的项目结构(如果组件B有我假设的模块),在遵循文档中所述的设置后,您可能需要在TranslateModule模块导入中添加Component B

@NgModule({
  imports: [ 
    TranslateModule,
    ...
  ],
  ...
})
export class ComponentB {}
相关问题