Angular pluralization with @ngx-translate and ngx-translate-messageformat-compiler doesn’t initialize properly

Viewed 6457

I performed the following steps

(1) Created a new angular-cli project (angular-cli 1.5.0)

(2) Added dependencies:

npm i @ngx-translate/core @ngx-translate/http-loader messageformat ngx-translate-messageformat-compiler --save

(3) Added JSON files with translations:

asserts/i18n/en.json

{
    "translation": "translation",
    "things": "{count, plural, =0{Nothing} one{One thing} other{Lots of things}}"
} 

asserts/i18n/de.json)

{
    "translation": "Übersetzung",
    "things": "{count, plural, =0{Nichts} one{Ein Ding} other{Viele Dinge}}"
}

(4) AppModule

import { AppComponent } from './app.component';

export function createTranslateLoader(http: HttpClient) {
  return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: (createTranslateLoader),
        deps: [HttpClient]
      },
      compiler: {
        provide: TranslateCompiler,
        useClass: TranslateMessageFormatCompiler
      }
    }),
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

(5) AppComponent

import { Component } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

@Component({
  selector: 'app-root',
  template: `
    <h1 translate>translation</h1>
    <p>{{'things' | translate:"{ count: 2 }"}}</p>
    <button (click)="selectLang('de')">De</button>
    <button (click)="selectLang('en')">En</button>
  `
})
export class AppComponent {

  constructor(private translate: TranslateService) {
    translate.setDefaultLang('de');
    this.translate.use('de');
    translate.addLangs(['en']);
  }

  selectLang(lang: string)  {
    this.translate.use(lang);
  }

}

The page loads without a problem and shows the simple translations properly ("Überschrift") but the pluralization is not working.

Curious, changing the language to en by clicking the button “En” has the desired result:

enter image description here

Now, switching back to “De” shows the desired result in german language too.

enter image description here

1 Answers
Related