【问题标题】:How to translate words in the component(.ts) Ngx Translation Angular如何翻译组件(.ts)中的单词 Ngx Translation Angular
【发布时间】:2021-02-04 23:34:01
【问题描述】:

我有这个数组,我从中构建表的标题,但我无法根据语言显示标题。我正在使用 ngx 翻译。

我的 html 模板中有这个:

  <thead>
                <tr>
                    <th>#</th>
                    <th *ngFor="let col of columns" class="cursor-pointer" (click)="sort(col.propertyName)">
                        {{col.label}}
                    </th>
                </tr>

            </thead>

我只得到 [object object]

我的 .ts 组件中有这个

columns = [
{ label: 'Nombre', propertyName: 'name' },
{ label: 'Imagen', propertyName: 'image' },
{ label: 'Descripción', propertyName: 'description' },
{ label: 'Categoria', propertyName: 'category' },
{ label: this.translateService.get('form.purchasePrice'), propertyName: 'purchase_price' },
{ label: 'Precio Unitario', propertyName: 'unit_price' },
{ label: 'Acción', propertyName: 'action' }];

尝试使用 translateService 获取、即时、流式传输

但我没有得到想要的结果

【问题讨论】:

    标签: angular translate ngx-translate


    【解决方案1】:

    对于每种语言,您的 Angular 应用程序资产中都会有一个单独的文件:

    • de.json
    • en.json
    • ...

    每个翻译文件都包含键值对,即。 e. en.json

    {
      "MY_LABEL": "My translation text"
    }
    

    de.json

    {
      "MY_LABEL": "Mein Übersetzungstext"
    }
    

    在您的模板中,您可以按如下方式使用翻译管道

    {{ 'MY_LABEL' | translate }}
    

    ngx 会根据选择的语言选择正确的翻译文件。

    因此,您的 columns 数组不应包含翻译后的值。它应该只包含标签。实际翻译的值应该只出现在您的翻译文件中。

    your.component.ts

    columns = [
      { label: 'YOUR_COMPONENT-NOMBRE', propertyName: 'name' }
    ]
    

    your.component.html

    {{ col.label | translate }}
    

    es.json

    {
      'YOUR_COMPONENT-NOMBRE': 'nombre'
    }
    

    usage guide 之后,您还必须在您的应用模块中进行一些配置。

    【讨论】:

    • 如果我需要将标签翻译成我的打字稿类。有没有办法用打字稿得到它?
    • @DEV_404_NF 是的,有办法。首先,注入翻译服务:constructor(translate: TranslateService)。然后简单地使用它translate.get('HELLO', {value: 'world'}).subscribe((res: string) =&gt; { console.log(res); });
    【解决方案2】:

    你可以为这个翻译做一件事。我假设您有它的 JSON 文件,并且您已经在当前使用的模块中添加了翻译模块。我遇到了同样的问题,这就是我的工作方式。

    在你的 ts 文件中:

    import { TranslateService } from "@ngx-translate/core";
    .
    .
    constructor (private translateService: TranslateService)
    .
    .
    public getTranslationsForTable(columns) {
    /// in your columns array do the translation for specific
    /// add a property to your col object which check if the label is already translated
    
    this.translateService.get(columns.label).toPromise().then(e => console.log(e)).catch(e => console.error(`Error is thrown ${e}`));
    }
    
    

    你正在做的是在对象中调用一个 get 方法,这是一个承诺,它没有解决,而是先尝试获取翻译,然后将翻译添加到列数组中。

    【讨论】:

    • 感谢您的帮助!
    猜你喜欢
    • 2020-06-30
    • 2020-03-10
    • 1970-01-01
    • 1970-01-01
    • 2018-09-30
    • 1970-01-01
    • 2017-07-26
    • 2022-06-23
    • 1970-01-01
    相关资源
    最近更新 更多