Home:ALL Converter>Angular translations with ngx-translate/core

Angular translations with ngx-translate/core

Ask Time:2019-11-11T08:39:31         Author:Jcbo

Json Formatter

I'm following this tutorial (https://alligator.io/angular/ngx-translate/) about translations in Angular. When I call the translation in HTML file nothing happen and I saw an empty line:

<label translate='demo.title'></label>

But in my component.ts, if I import the import {TranslateService} from '@ngx-translate/core'; I can get the right translation using:

title:string;
constructor(private translate: TranslateService) { }
ngOnInit() {

  this.translate.get(['demo.title'])
    .subscribe(translations => {
      this.title = translations['demo.title'];
      console.log(this.title ); // the right translations appears in console
    });
}

app.module.ts

// import ngx-translate and the http loader
import {TranslateLoader, TranslateModule} from '@ngx-translate/core';
import {TranslateHttpLoader} from '@ngx-translate/http-loader';


@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HomeModule,
    IndexModule,
    NoPageModule,
    HttpClientModule,
    // ngx-translate and the loader module
    TranslateModule.forRoot({
        loader: {
            provide: TranslateLoader,
            useFactory: HttpLoaderFactory,
            deps: [HttpClient]
        }
    }),
    RouterModule.forRoot(routes, { useHash: true }),
  ],
  providers: [AuthService, AuthGuard],
  bootstrap: [AppComponent],
  schemas:[CUSTOM_ELEMENTS_SCHEMA]
})
export class AppModule {}

// required for AOT compilation
export function HttpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(http);
}

pt.json

{
  "demo": {
    "title": "oi",
    "text": "This is a simple demonstration app for ngx-translate"
  }
}

Related to this topic, how can I know with Angular the browser language?

Best regards

Author:Jcbo,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/58794271/angular-translations-with-ngx-translate-core
yy