繁体   English   中英

Angular 中动态内容的国际化?

[英]Internationalization of dynamic content in Angular?

Angular.io 对 i18n 标签的描述如下:

Angular i18n 属性标记可翻译的内容。 将其放置在要翻译固定文本的每个元素标签上。

所以我的问题是这个。 如果我有一个内容是动态的元素怎么办? 以下表为例,该表显示了资产列表。 在某些情况下,“描述”列需要使用英语,在某些情况下需要使用其他语言。

    <table class="asset-table">
      <thead>
        <tr>
          <th i18n="@@alarm-list-timeon">Time On</th>
          <th i18n="@@alarm-list-timeoff">Time Off</th>
          <th i18n="@@alarm-list-asset">Asset</th>
          <th i18n="@@alarm-list-description">Description</th>
        </tr>
      </thead>
      <tbody *ngIf="showAssets">
        <tr *ngFor="let asset of pageItems">
          <td>{{asset.timeon}}</td>
          <td>{{asset.timeoff}}</td>
          <td>{{asset.assetlabel}}</td>
          <td i18n>{{asset.description}}</td>
        </tr>
      </tbody>
    </table>

我在想这样的事情:

    <table class="asset-table">
      <thead>
        <tr>
          <th i18n="@@alarm-list-timeon">Time On</th>
          <th i18n="@@alarm-list-timeoff">Time Off</th>
          <th i18n="@@alarm-list-asset">Asset</th>
          <th i18n="@@alarm-list-description">Description</th>
        </tr>
      </thead>
      <tbody *ngIf="showAssets">
        <tr *ngFor="let asset of pageItems">
          <td>{{asset.timeon}}</td>
          <td>{{asset.timeoff}}</td>
          <td>{{asset.assetlabel}}</td>
          <td i18n="@@{{asset.description}}">{{asset.description}}</td>
        </tr>
      </tbody>
    </table>

……但我错了。 有什么建议么?

首先,i18n 值是一个 ID,因此它始终是静态的。

其次,就翻译更改的内容而言,我唯一的成功是在模板中使用NgSwitch的解决方法。

在此示例中, thingStatus是您的变量,其可能的值为“good”、“bad”和“unknown”。 所有这些都是一个单独的翻译项目,具有自己的 i18n ID 值。

显然,如果thingStatus可能有无法管理的数量,这将失败。

    <div [ngSwitch]="thingStatus">
        <p *ngSwitchCase="good" i18n="status_good>Good</p>
        <p *ngSwitchCase="bad" i18n="status_bad>Bad</p>
        <p *ngSwitchCase="unknown" i18n="status_unknown>Unknown</p>
    </div>

使用这种结构

<span
  i18n="status text|Status text@@statusText"
>{
  asset.statusLangCode, select,

  bad {Bad}
  good {Good}

  other {Unknown}
}</span>

并且在翻译文件中会生成一个这样的结构(目标是手动添加的)

<source>{VAR_SELECT, select, good {Good} bad {Bad} other {Unknown}}</source>
<target>{VAR_SELECT, select, good {Хороший} bad {Плохой} other {Неизвестный}}</target>

有关更多信息,请参阅https://angular.io/guide/i18n#translate-select

假设您的后端服务返回已知的可能值,您可以执行以下操作:

const values = ['admin', 'teacher', 'librarian']

将转换后的值添加到sv_SE.json给定先前的值作为键

role: {
  "admin": "admin",
  "teacher": "lärare",
  "librarian": "Bibliotekarie"
}

app.component.html调用翻译

<div *ngFor="let value of values">
{{ ('role.' + value) | translate }}
</div>

暂无
暂无

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

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