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.

module A

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

export class BComponent implements 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. the translation will not happen on the 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.

1 answer

  • answered 2019-05-15 03:32 Tony Ngo

    I think you should inject into app.component.ts like document said

    1. First import the 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:
    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');
        }
    }