Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 and i18n in typescript

I saw that angular6 implements i18n for its components and that by using i18n you can internationalize your html but can you do the same with typescript? I have two specific areas

One in a zingChart: - Be able to i18n Example

exampleData = {
 valueBox: {
                text: '<span style="font-size: 32px">%pie-total-value</span> <br/> Example',
                placement: 'center',
                fontWeight: 'normal'
            },
     }

Thank you very much for your time and answers.

like image 800
user173092 Avatar asked Sep 19 '18 14:09

user173092


Video Answer


2 Answers

This is not possible through the library's API until now (@angular/language-service v7.2).

Below is my workaround (thank fredrikredflag for his good post on GitHub and thank @BrunoBruzzano for the link):


src/app/i18n.service.ts:

import {Injectable} from "@angular/core";
import {Xliff2} from '@angular/compiler';
// You can also import {Xliff} or {Xtb} instead of {Xliff2}, depending on your project configurations

declare const require;
const content = require('raw-loader!../i18n/messages.fa.xlf');

@Injectable({
    providedIn: 'root'
})
export class I18nService {
    private readonly xliff: any = new Xliff2().load(content, '');

    get(key: string): string {
        return this.xliff.i18nNodesByMsgId[key][0].value;
    }
}

i18n pseudo-component (JUST FOR AUTO-GENERATING TRANSLATIONS in messages.xlf file):

  1. src/app/i18n/i18n.component.ts (Isn't important. Just needed to exists.):

    import {Component} from '@angular/core';
    @Component({templateUrl: './i18n.component.html'})
    export class I18nComponent {}
    
  2. src/app/i18n/i18n.component.html (don't forget using an id!)

    <p i18n="@@newVersionAlert">New version available. Load New Version?</p>
    

Don't forget declaring I18nComponent in your @NgModule.


Usage (after running ng xi18n ... and translating):

In your component:

...
import {I18nService} from './i18n.service';

...
    constructor(private i18nService: I18nService, ...) { ... }

    sampleUsage() {
        confirm(this.t('newVersionAlert'));
    }

    /**
     * translate
     */
    private t(i18nId: string) {
        return this.i18nService.get(i18nId);
    }
...

Utility script to translate i18n.service.ts before build:

(This requirement: require('raw-loader!../i18n/messages.fa.xlf') needs to be translated to match wanted locale.)

PreBuild/prebuild.ts:

import {Xliff2} from "@angular/compiler";  
// You can also import {Xliff} or {Xtb} from "@angular/compiler" depending of your case.

const fs = require('fs');  
const path = require('path');  

const localeId = process.argv[2];  

if (localeId === undefined) throw new Error(`No language specified.\nUsage: node ${path.basename(__filename)} <locale-id${'>'}`);  

const content = fs.readFileSync(`src/i18n/messages.${localeId}.xlf`, 'utf8');  
const xliff = new Xliff2().load(content, '');

const i18nServiceFilePath = './src/app/i18n.service.ts'; 

fs.writeFileSync(i18nServiceFilePath,  
  fs.readFileSync(i18nServiceFilePath, 'utf8')  
    .replace(/(raw-loader!\.\.\/i18n\/messages\.)\w{2}(\.xlf)/, `$1${xliff.locale}$2`)  
);

PreBuild/tsconfig.json:

{
    "compilerOptions": {
        "outDir": "./build",
        "lib": [
            "es2018",
            "dom"
        ],
        "module": "commonjs",
        "moduleResolution": "node",
        "target": "es6",
        "typeRoots": [
            "../node_modules/@types"
        ]
    },
    "files": [
        "prebuild.ts"
    ]
}

package.json:

...
"scripts": {
    "compile-pre-build": "tsc -p PreBuild/tsconfig.json --pretty",
    "pre-build": "node PreBuild/build/prebuild.js",
    ...
...

Usage:

(After one-time npm run compile-pre-build:)

npm run pre-build -- fa

or

npm run pre-build -- en

This will edit i18n.service.ts.

like image 65
Mir-Ismaili Avatar answered Nov 14 '22 22:11

Mir-Ismaili


In Angular 9 you can use global $localize function like this:

$localize`String to translate`

Be aware:

  1. In Angular 9 CLI does not extract these messages with the xi18n, you have to do it manually
  2. Run ng add @angular/localize if you have not gone through $localize migration
like image 31
Ed Kolosovsky Avatar answered Nov 14 '22 21:11

Ed Kolosovsky