【问题标题】:Angular 8 i18n translate dynamic variableAngular 8 i18n 转换动态变量
【发布时间】:2020-02-12 19:37:54
【问题描述】:

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

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

我有一个包含 setter 和 getter 的共享服务:

...
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 时,我会看到 Product,这很酷。

如何动态翻译仪表板和产品,因为 {{title}} 会根据页面而变化。

我的xlf 制作了这个:

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

我添加了目标标签,但不确定这是否适合翻译。

任何想法。谢谢

【问题讨论】:

    标签: angular angular-i18n


    【解决方案1】:

    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 的支持?
    • 另外,如何将其与可观察的打字等一起使用?您的标题变量不再是可观察的......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-24
    • 1970-01-01
    • 1970-01-01
    • 2018-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多