Make simple ng2-translate translation work in HTML template

1.5k views Asked by At

I just added ng2-translate (5.0.0) to our angular (2.4.1) + typescript (2.0.3) + webpack (2.1.0-beta.25) project. I'm defining translations manually through setTranslation and some dictionaries in memory, early on at construction time.

When I use TranslateService within Component code, everything works fine. Now I'm not able to find the right syntax for neither the directive nor the pipe within HTML template.

One set of translation has, for example:

en = {
  ...
  loginTitle: 'Please log in',
  ...
}

1) Pipe

When template has:

<h3 class="panel-title">{{ 'loginTitle' | translate }}</h3>

application breaks at runtime, at a very early stage, on platformBrowserDynamic().bootstrapModule(AppModule) with

Error while bootstrapping application. SyntaxError

2) Directive + Content

When template has:

<h3 class="panel-title" translate>loginTitle</h3>

application does not break, but page just shows untranslated key, loginTitle.

3) Directive

When template has:

<h3 class="panel-title" [translate]="'loginTitle'"></h3>

application does not break, but page does not show any text where that should be, the DOM node wraps no text.

As recommended in docs, I've imported TranslateModule both at app-module level (with forRoot) as well as in a shared module, which in turn gets imported by other area modules.

I also tried other variations, with nested translations, without single quotes, and so on, with no luck. What am I doing wrong?

EDIT In scenario #1 I was able to log more info on initial error:

Error: Template parse errors: The pipe 'translate' could not be found

but that should be part of ng2-translate already

1

There are 1 answers

0
superjos On BEST ANSWER

After some trial and error, and after working on a plunker step-by-step, I found the issue. The shared module was importing TranslateModule, but it was not exporting it as well for others to use (doh!)

import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
...
import { TranslateModule } from 'ng2-translate';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    ...
    TranslateModule,
    ...
  ],
  exports: [
    ...
    TranslateModule, // <-- this was missing initially
  ],
})
export class SharedModule {
 ...
}