Translation in the Template

Structural Directive

The structural directive is the recommended approach as it is DRY (Don't Repeat Yourself) and efficient. It creates a single subscription per template, making it an optimal choice for translations:

<ng-container *transloco="let t">
  <p>{{ t('title') }}</p>
  <comp [title]="t('title')"></comp>
</ng-container>

The t function is memoized, meaning it caches translation results. If the same key is requested again, it will return the cached value for better performance.

You can also pass a params object as the second argument:

home.component.html
<ng-container *transloco="let t">
  <p>{{ t('name', { name: 'Transloco' }) }}</p>
</ng-container>

And here is how that translation looks like:

en.json
{
  "name": "My name is {{name}}"
}

To translate based on a different language, specify the lang input:

home.component.html
<ng-container *transloco="let t; lang: 'es'">
  <p>{{ t('title') }}</p>
</ng-container>

This will use the Spanish translation file to translate the keys.

Using the prefix Input

The read input was renamed to prefix starting with v7.1.0. The old read input is now deprecated and will be removed in v8.

You can use the prefix input in the structural directive to get translations for nested properties (including deeply nested ones). This eliminates the need to repeatedly specify the same parent key in your translations.

Let's look at the following JSON file:

en.json
{
  "foo": "Foo",
  "bar": "Bar",
  "dashboard": {
    "title": "Dashboard Title",
    "desc": "Dashboard Description"
  }
}

And here's how we use the prefix in the template:

<ng-container *transloco="let t; prefix: 'dashboard'">
  <p>{{ t('title') }}</p>
  <p>{{ t('desc') }}</p>
</ng-container>

When you pass a prefix, Transloco treats the keys as if you had written them like this:

<ng-container *transloco="let t;">
  <h1>{{ t('dashboard.title') }}</h1>
  <p>{{ t('dashboard.desc') }}</p>
</ng-container>

Pipe

Another option is using the transloco pipe:

<span>{{ 'home' | transloco }}</span>

You can use it with params:

<span>{{ 'alert' | transloco: { value: dynamic } }}</span>

It can also be used with bindings or inputs:

<span [attr.alt]="'hello' | transloco">Attribute</span>
<span [title]="'hello' | transloco">Property</span>
<my-comp [label]="'hello' | transloco" />

To translate using a different language:

<span>{{ 'alert' | transloco:params:'es' }}</span>

Attribute Directive

Finally, you can use the transloco attribute directive:

<span transloco="home"></span>

Use it with params:

<span transloco="alert" [translocoParams]="{ value: dynamic }"></span>

To specify a different language:

<span transloco="home" translocoLang="es"></span>

Last updated

Was this helpful?