【问题标题】:Angular 10: Translate strings known to i18n in variables at runtimeAngular 10:在运行时在变量中翻译 i18n 已知的字符串
【发布时间】:2020-11-03 11:10:13
【问题描述】:

是否有可能通过调用以下代码来翻译 Angular 10 中 i18n 已知的字符串:

translate(myText);

其中 'myText' 是一个变量,其中包含 i18n 已知的字符串。

一个简单的例子。我在 HTML 中有这段代码:

<div i18n>This is a simple Test.</div>

然后我想在代码中做这样的事情:

const transText = translate('This is a simple Test.');

括号中的文字仅用于示例,它不会在编译时出现在代码中。实际上,它将来自一个字符串,该字符串传递给无法用 i18n 或 i18n-Attribute 标记的自定义 html 元素。也不可能在代码中用 $localize ... 标记它。

文本将与使用 i18n-Attribute 或 $localize 定义的完全相同。

我想到解决这个问题的一件事是解析语言文件,我在启动时将其作为 json 结构提供给应用程序,但为此我需要知道为该文本生成的 id .我得到的另一个想法是在原始 XLF 文件中查找文本,获取该 ID 并在翻译后的结构中搜索它。

但是这两个版本都不是很好,对我来说似乎很成问题,因为它们依赖于不改变 Angular 中 i18n 的工作方式。我希望有一种内部方式来翻译这样的字符串。

【问题讨论】:

    标签: angular internationalization


    【解决方案1】:

    简短的回答不是。你可以有一个“翻译(文本)”。好吧,总是可以调用 API。我知道的更接近的尝试是使用transcolo,并且有一些解决方法。我不知道这个已经快 2 岁的SO 的想法是什么,this another SO 可以帮助你。随着时间的推移,我改进了一些想法,虽然实际上是一样的:

    组件翻译

    @Component({
      selector: 'ng-translation',
      template: `<div *ngIf="!yet" style="display:'none'">
                <ng-content></ng-content>
                </div>`
    })
    
    export class AppTranslationComponent implements AfterContentInit {
      @ContentChildren(AppTextComponent, { read: ElementRef }) divs: QueryList<ElementRef>;
      data: any
      yet: boolean = false;
      get(text: string, ...args: any[]) {
        if (!this.data)
          return "";
        let response = this.data[text];
        if (response && response.match(/\[.\]/))
          response.match(/\[.\]/g).forEach((l, i) => {
            response = response.replace(l, args[i])
          })
        return response
      }
      ngAfterContentInit(): void {
        if (this.divs.length) {
          this.data = {}
          this.divs.forEach(c => {
            this.data[c.nativeElement.id] = c.nativeElement.innerHTML
          })
          setTimeout(() => {
            this.yet = true;
          })
        }
      }
    

    还有一个组件文本

    @Component({
      selector: 'text',
      template: `<ng-content></ng-content>`
    })
    export class AppTextComponent { }
    

    在任何组件中:

    <ng-translation>
      <text id="one1" i18n="@@component-one1">This is the one1</text>
      <text id="one2" i18n="@@component-one2">this is the one2 [0] greatting</text>
      <text id="one3" i18n="@@component-sum">The sum of [0] and [1] is [3]</text>
    </ng-translation>
    
    @ViewChild(AppTranslationComponent, { static: true }) t: any
    

    你可以使用

      const value=this.t.get('one1');
      const value2=this.t.get('one2','Peter');
    

    或在 .html 中

      {{t.get('one3',2,3,5}}
    

    【讨论】:

      猜你喜欢
      • 2018-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-15
      • 1970-01-01
      相关资源
      最近更新 更多