简体   繁体   English

ngx-translate 在模块的所有子组件中进行翻译

[英]ngx-translate translating in all children components of the module

I am currently using ngx-translate on the angular 7. My project is translating two languages, english and chinese, the project is composed of the structure as showed below, A.component is the parent component and B.component is the children component.我目前在angular 7上使用ngx-translate。我的项目正在翻译两种语言,英语和中文,该项目由如下所示的结构组成,A.component是父组件,B.component是子组件。

module A模块A

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

export class BComponent implements OnInit{导出类 BComponent 实现 OnInit{

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

the code above is working to translate.上面的代码正在翻译。

But if the above code is only added to A.component but not B.component.但是如果上面的代码只加到A.component而不是B.component。 the translation will not happen on the B.component.翻译不会发生在 B.component 上。

I wonder if there is the way to have the code added to parent component of the module, and all the following children components can automatically translate without putting the code in each children component.不知道有没有办法把代码加到模块的父组件上,后面所有的子组件都可以自动翻译,不用把代码放到每个子组件里。

I think you should inject into app.component.ts like document said 我认为您应该像文档中所说的那样注入app.component.ts

  1. First import the TranslateModule: 首先导入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. Init the TranslateService for your application: 为您的应用程序初始化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');
    }
}

Depending on your project structure (if Component B has its own module which i am assuming), you may need to add TranslateModule in your Component B module imports after following the setup stated in the documentation.根据您的项目结构(如果组件 B 有我假设的自己的模块),您可能需要按照文档中所述的设置在Component B模块导入中添加TranslateModule

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM