簡體   English   中英

ngx-translate 在模塊的所有子組件中進行翻譯

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

我目前在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 上。

不知道有沒有辦法把代碼加到模塊的父組件上,后面所有的子組件都可以自動翻譯,不用把代碼放到每個子組件里。

我認為您應該像文檔中所說的那樣注入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');
    }
}

根據您的項目結構(如果組件 B 有我假設的自己的模塊),您可能需要按照文檔中所述的設置在Component B模塊導入中添加TranslateModule

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM