Extracting $localize messages from typescript not working in Angular 9

Viewed 2298

I thus far know that I can extract i18n messages (from html) by doing ng xi18n. But I have also some text in typescript that needs to be translated. I am making use of $localize like this: $localize':@@info:It's green!'. If I run ng xi18n, it doesn't extract the text with $localize. I am using Angular 9. Maybe it's a feature that only works in Angular 10? if so, would running the xi18n command do the trick?

3 Answers

The whole new updates are still somewhat undocumented, but for the ng xi18n you will need to add --ivy for now.

Eventually this should not even use xlf files anymore, but be loaded in polyfill as object map (extracting into that form is not automatically done yet though).

I got the same issue even with angular cli v10. I tried with the --ivy option but I got the same issue. I found a workaround: since only the extraction to xlf files doesn't work but the translation after build:prod is well effective even for the $localize in the ts files, when I have something to translate which is only in a ts file, I add the words to translate in the html file of the component in a ng-container I never display. Then it's as usual, when I run the ng xi18n I can find the words I need in the xlf file and translate them.

html file:

<!-- my regular content -->
<p> this is the regular content of my html file</p>

<!-- The words in my ts files I need to translate with
displayi18n always to "false" so it is never displayed-->
<ng-container *ngIf="displayi18n">
  <span i18n="@@settings">Paramètres</span>
  <span i18n="@@users">Utilisateurs</span>
</ng-container>

and in my ts file:

@Component ...
export class MyComponent ...
  ...
  // Var to tell ngIf to not display the ng-container for i18n
  public displayi18n: boolean = false;
  
  // Where I need the translated words:
  public settings_label: string = $localize`:@@settings:Paramètres`
  public users_label: string = $localize`:@@users:Utilisateurs`
  ...

As your app is localization enabled (ng add @angular/localize ) then in your app's angular.json file, you can add "ivy":true to options under extract-i18n attribute as below: "extract-i18n": { "builder": "@angular-devkit/build-angular:extract-i18n", "options": { "browserTarget": "commons-admin:build", "ivy":true } } Then you will see that i18n-extraction is not only excracting HTML files but also *.ts files which are using $localize format.

Related