Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use Angular i18n to translate string literals in typescript code

I'm localizing my Angular app using Angular's i18n tools, which extract text from HTML templates into an xlf file, and then build a localized version of the whole app using AOT (ahead of time compilation).

My question is: Can is use this framework to extract string literals in typescript code, so they are listed in the same xlf file and replaced in the localized AOT build?

Ideally, I'd like to write something like this in my typescript code:

foo() {
   this.bar = i18n('baz');

and the string 'baz' would be listed in the xlf file I send to my translator.

Alternatively, if this isn't possible, is there a library that does something similar? I.e. extract strings from typescript code into an xlf file, then replaces them either at runtime or during build?

like image 837
Niki Avatar asked Mar 06 '18 06:03

Niki


People also ask

What is the purpose of i18n attribute?

I18N Attribute Collection. This attribute indicates the language of an element's attribute values and text content, and of all elements it contains, unless overridden. It is defined normatively in [XML] section 2.12. The default value of this attribute is unspecified.

What is i18n Angular?

Angular Internationalizationlink Internationalization, sometimes referenced as i18n, is the process of designing and preparing your project for use in different locales around the world. Localization is the process of building versions of your project for different locales.

Which one of the following Angular CLI commands will extract the marked text for translation in the application and create a translation source file?

After you prepare a component for translation, use the extract-i18n Angular CLI command to extract the marked text in the component into a source language file.


1 Answers

I can confirm what @JB Nizet is referring to in his answer is now working in Angular 9, so this works:

  foo() {
    const appTitle = $localize`:@@siteTitle:Example Title`;
    // appTitle is now translated based on locale

    titleService.setTitle(appTitle); 
  }

You can read more about it here https://github.com/angular/angular/blob/master/packages/localize/init/index.ts

like image 55
azerafati Avatar answered Nov 02 '22 23:11

azerafati