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:
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:
And here is how that translation looks like:
To translate based on a different language, specify the lang
input:
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:
And here's how we use the prefix
in the template:
When you pass a prefix, Transloco treats the keys as if you had written them like this:
Pipe
Another option is using the transloco pipe:
You can use it with params:
It can also be used with bindings or inputs:
To translate using a different language:
Attribute Directive
Finally, you can use the transloco attribute directive:
Use it with params:
To specify a different language:
Last updated
Was this helpful?