Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 - Translating Strings in TypeScript

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?

like image 910
AJM Avatar asked Dec 01 '17 10:12

AJM


3 Answers

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.

like image 84
Mir-Ismaili Avatar answered Oct 23 '22 13:10

Mir-Ismaili


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>
like image 45
AbhijithKA Avatar answered Oct 23 '22 14:10

AbhijithKA


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.

like image 2
Bruno Bruzzano Avatar answered Oct 23 '22 14:10

Bruno Bruzzano