Angular 8 i18n 动态变量翻译

3

我在我的 app.component.html 文件中有一个出现在每个页面上的元素:

<h1 i18n="@@titleH1">{{title}}</h1>

我有一个共享服务,它拥有设置器(setters)和获取器(getters):

...
title = new BehaviorSubject('Initial Title');

setTitle(title: string) {
this.title.next(title);
}
...

app.component.ts: ngOnInit

...
this.sharedService.title.subscribe(updateTitle => this.title = updateTitle);
this.sharedService.setTitle('Dashboard');
...`

product.component.ts: ngOnInit

...
this.sharedService.title.subscribe(updateTitle => this.title = updateTitle);
this.sharedService.setTitle('Product');
...

当我导航到 /dashboard 时, 标签中会显示“Dashboard”,当我导航到 /product 时,<title> 标签中会显示“Product”,这很棒。</br><div class="h-2"></div>如何动态地将“Dashboard”和“Product”翻译为 {{title}},以便根据页面更改。</br><div class="h-2"></div>我的 <code>xlf</code> 生成了以下内容:</br><div class="h-2"></div><pre class="guess-HTML"><code> ... <trans-unit id="titleH1" datatype="html"> <source><x id="INTERPOLATION" equiv-text="{{title}}"/></source> <target><x id="INTERPOLATION" equiv-text="{{title}}"/></target> <context-group purpose="location"> <context context-type="sourcefile">src/app/app.component.html</context> <context context-type="linenumber">17</context> </context-group> </trans-unit> ... </code></pre></br><div class="h-2"></div>我已经添加了目标标签,但不确定它如何适合翻译。有什么想法吗?谢谢。
1个回答

3

现在有Angular 9,其中包含新的$localize功能,可以轻松实现以下操作。

app.component.html:

<h1>{{title}}</h1>

app.component.ts:

...
title = $localize`:@@dashboard:Dashboard`;
...
this.sharedService.setTitle(this.title);

product.component.ts:

...
title = $localize`:@@product:Product`;
...
this.sharedService.setTitle(this.title);

messages.xlf:

<trans-unit id="dashboard">
  <source>Dashboard</source>
  <target>Translation here</target>
</trans-unit>
<trans-unit id="product">
  <source>Product</source>
  <target>Translation here</target>
</trans-unit>

很棒的 @Angular 团队!


只是一个提醒,因为似乎 i18n 生成器尚未捕获这些字符串,因为这不是 Angular 团队正式支持的。也许我们会在 Angular 10 上看到支持? - Gabriel G.
还有如何在可观察类型等方面使用它?您的标题变量不再是可观察的... - JoshuaTree

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