繁体   English   中英

如何翻译组件中的单词(.ts) Ngx Translation Angular

[英]How to translate words in the component(.ts) Ngx Translation Angular

我有这个数组,我从中构建表的标题,但我无法根据语言显示标题。 我正在使用 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] 我只得到 [object object]

我在 my.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获取,即时,stream

但我没有得到想要的结果

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

  • de.json
  • zh.json
  • ...

这些翻译文件中的每一个都包含键值对,即en.json

{
  "MY_LABEL": "My translation text"
}

de.json

{
  "MY_LABEL": "Mein Übersetzungstext"
}

在您的模板中,您可以使用翻译 pipe 如下

{{ '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'
}

按照使用指南,您还必须在应用程序模块中进行一些配置。

你可以为这个翻译做一件事。 我假设您有 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}`));
}

您正在做的是在 object 中调用 get 方法,这是一个 promise 并且没有解决,而是先尝试获取翻译,然后将翻译添加到列数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM