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