Translating your components
This content is for v15. Switch to the latest version for up-to-date documentation.
ngx-translate allows you to easily integrate translations into both your templates and code.
Using Translations in Templates
Using translations in the templates is straight forward. You just have to make sure, that the
TranslateModule
is available in the component.
If you are using NgModules, there’s nothing to do inside the component itself. The import is either
in the app.module.ts
or the module itself.
When using standalone components, import the TranslateModule
like this:
TranslatePipe
Basic usage
The easiest way to translate text is using the TranslatePipe
With parameters
It’s also possible to add parameters like this:
And in your component define name
like this:
In the language file, use {{name}}
as placeholder:
TranslateDirective
This is how you use the directive:
Or even simpler using the content of your element as a key:
Using HTML Tags in Translations
You can easily use raw HTML tags within your translations.
To render them, simply use the innerHTML
attribute with the pipe on any element.
[innerHTML]
should be safe to use because it uses Angular’s DomSanitizer
to filter potentially harmful tags like
<script>
or <style>
.
Using Translations in Code
To use translations in your code, you need to utilize Dependency Injection in the constructor to access the TranslateService. This service allows you to load translations, switch languages, and retrieve translated messages directly within your application logic.
You might wonder why the get()
method
uses a subscription to retrieve translations. The reason is that your language
file might not be loaded at the time the get()
function is called, so the
update is triggered once the file finishes loading.
Alternatively, you can use stream()
,
which works similarly to get()
but has the added benefit of firing again
whenever the language changes. This ensures the translation stays up to date
even if the user switches languages.
For cases where you need an immediate, synchronous translation result, you can
use instant()
. This method returns
the translation instantly but only works if the translation file is already
loaded or if translations have been manually set using
setTranslation()
.
Using Dynamic Ids
You can construct the translation keys dynamically by using simple string concatenation inside the template:
Where languages
is an array member of your component:
You language file would look like this;
You can also use the output of the built-in pipes uppercase
and lowercase
in order to guarantee
that your dynamically generated translation keys are either all uppercase or all lowercase. For example:
will match the following translation: