Angular中动态内容的国际化?

3

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

Angular i18n属性用于标记可翻译的内容。在每个需要翻译的固定文本元素标签上添加此属性。

那么我的问题是,如果我有一个内容动态的元素呢?例如下面的表格显示了一系列资产。"Description"列在某些情况下需要使用英语,在其他情况下需要使用其他语言。

    <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>

...但我错了。有什么建议吗?


Angular i18n是静态的,不是动态的。 - Ploppy
3个回答

4

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

其次,对于翻译变化的内容,我唯一成功的方法是在模板中使用NgSwitch的解决方法。

在这个例子中,thingStatus是你的变量,它可能的值是“好的”,“坏的”和“未知的”。所有这些都将是单独的翻译项目,具有自己的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>

2
使用这个结构。
<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

-1
假设您的后端服务返回已知的可能值,您可以执行以下操作:
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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接