Angular 5 - Translating Strings in TypeScript
Asked Answered
L

3

8

I am using i18n for my tranlsations and am happy with how this works on the html side.

However if I have error messages etc defined in strings in my typescript I would like a way to translate these and can't find a way to do it.

Is there a workaround to achieve this?

Labonte answered 1/12, 2017 at 10:52 Comment(0)
V
3

This is not possible through the library's API until now (@angular/language-service v7.2). Anyway, you can see my answer under another similar question for a workaround.

Vorticella answered 14/2, 2019 at 6:51 Comment(1)
This looks exactly like what I was looking for, and should probably be the accepted answer, thanks!Moncrief
I
3

With Angular 9+ you can do this

let <local_variable> = $localize`:@@<unique_id>:<optional_text>`

Example: let err_msg = $localize`:@@err_username:Invalid username, please check your inputs`;

As of now you cannot auto extract these variables automatically using npm script. You have to manually add it like this

In messages.xlf file

<trans-unit id="err_username:Invalid" datatype="html">
      <source>Invalid username, please check your inputs</source>
</trans-unit>

In messages.lang.xlf file (translation file for language

 <trans-unit id="err_username:Invalid" datatype="html">
      <source/>
      <target>Ungültiger Benutzername, bitte überprüfen Sie Ihre Eingaben</target>
 </trans-unit>
Innervate answered 26/5, 2020 at 10:39 Comment(1)
This is correct, but keep in mind that this is not officially supported yet. Translations made in TypeScript will not be supported by xi18n and in Angular Libraries this will cause issues since they must be published without Ivy (v9)Fallal
S
2

There is an open question on Angular GitHub repo.

For more info, check this out. Unfortunately, typescript's strings are not supported yet officially. However, some devs proposed a few workarounds you could take a look at.

Scend answered 8/1, 2018 at 10:13 Comment(1)
the final solution there is to use github.com/ngx-translate - this lib support angular 7 and also translate inside typescript class and not only inside templatesPyongyang

© 2022 - 2024 — McMap. All rights reserved.