Angular 6 - How to extract translation from typescript

别来无恙 提交于 2021-02-18 08:34:09

问题


I am using Angular 6 and I have setup handling of translations according to the documentation found here: https://angular.io/guide/i18n.

The problem is that the documentation does not explain how to get translations using typescript.

There is a similar question here: Can I use Angular i18n to translate string literals in typescript code

But i cannot use that answer since it relies on ngx-translate which will be deprecated once Angular catches up, see https://github.com/ngx-translate/core/issues/495.

So using the Angular 6 i18n - how would i get the translated text using typescript based on for example an id?


回答1:


@Diemauerdk, the documentation not explain how get translations using typescript because this is not possible. A work-around can be has in several .ts the translations. That's

//file locale-us.ts
export const translation:any={
   greeting:"Hello World!",
   mainTitle:"The best Appliacion of the world"
}
//file locale-es.ts
export const translation:any={
   greeting:"¡Hola Mundo!",
   mainTitle:"la mejor aplicación del mundo"
}

In your .ts you can have a pipe

import { Pipe, PipeTransform } from '@angular/core';
import { translation } from '../../i18n/locale-us';


@Pipe({ name: 'translation' })
export class TranslationPipe implements PipeTransform {
    constructor() {}
    transform(value: string): string {
        return translation[value] || null;
    }
}

And you can use in a component where you inject the pipe in constructor some like

constructor(private translate: TranslationPipe){}
//And use like

alert(this.translate.transform('greeting'));

Then you can use the apart "fileReplacements" in angular.json. not show all the angular.json else where you must add the fileReplacement. You has a fe.g. of this if you download the i18n example of the documentation https://angular.io/guide/i18n#internationalization-i18n

  "configurations": {

   "production": {
        ...
    },
    "production-es": {
      "fileReplacements": [
        {
          "replace": "src/environments/environment.ts",
          "with": "src/environments/environment.prod.ts"
        }, //add this two lines
        {
          "replace": "src/i18n/locale-us.ts",
          "with": "src/i18n/locale-es.ts"
        }
      ],
      ...
      "outputPath": "dist/my-project-es/",
      "i18nFile": "src/locale/messages.es.xlf",
      ...
    },
    "es": {
      //And add this too
      "fileReplacements": [
        {
          "replace": "src/i18n/locale-us.ts",
          "with": "src/i18n/locale-es.ts"
        }
      ],
      ...

     "outputPath": "dist/my-project-es/",
      "i18nFile": "src/locale/messages.es.xlf",
      ...
    }
  }


来源:https://stackoverflow.com/questions/52498997/angular-6-how-to-extract-translation-from-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!