Angular 角度10:在运行时在变量中转换i18n已知的字符串

Angular 角度10:在运行时在变量中转换i18n已知的字符串,angular,internationalization,Angular,Internationalization,是否有可能通过调用以下命令在代码中转换i18n在Angular 10中已知的字符串: translate(myText); 其中“myText”是一个变量,包含i18n已知的字符串 一个简单的例子。我有以下HTML代码: <div i18n>This is a simple Test.</div> 括号中的文本仅用于示例,它不会在编译时出现在代码中。实际上,它来自一个字符串,该字符串被传递给一个不能用i18n或i18n属性标记的自定义html元素。此外,无法在代码中使

是否有可能通过调用以下命令在代码中转换i18n在Angular 10中已知的字符串:

translate(myText);
其中“myText”是一个变量,包含i18n已知的字符串

一个简单的例子。我有以下HTML代码:

<div i18n>This is a simple Test.</div>
括号中的文本仅用于示例,它不会在编译时出现在代码中。实际上,它来自一个字符串,该字符串被传递给一个不能用i18n或i18n属性标记的自定义html元素。此外,无法在代码中使用$localize
对其进行标记

文本将与使用i18n属性或$localize定义的文本完全相同

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


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

简单的答案是没有。你可以有一个“翻译(texto)”。嗯,始终可以调用API。我所知道的越接近的尝试是使用和有一些解决办法。我不知道这个想法已经有将近2年的历史了,可以帮助你。随着时间的推移,我对这个想法做了一些改进,尽管实际上是一样的:

组件翻译

@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;
      })
    }
  }
或者在.html中

  {{t.get('one3',2,3,5}}
@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');
  {{t.get('one3',2,3,5}}