【问题标题】:Angular Pipes with template strings that are inserted through [innerHTML]带有通过 [innerHTML] 插入的模板字符串的 Angular 管道
【发布时间】:2021-09-10 13:49:30
【问题描述】:

我试图在最近完成的 Angular 项目之一中实现 ngx-translate。在项目中,我们有一个组件通过innerHTML 在某个div 内呈现HTML 文件。现在,当我打算使用管道根据语言转换 HTML 文件文本时,我想将 HTML 字符串中的文本与模板字符串绑定,如下所示:

     <tr>
                    <th class="border-top-0">${this.test}</th>
    // the above is just to verify is pipe works as it will later be changed to:
// ${'HELLO' | translate:param} 
                    <th class="border-top-0">Description</th>
                    <th class="border-top-0">Action?</th>
                </tr>

我准备要在组件内呈现的 HTML 文件的方式:

component.ts:

 this._httpClient.get(path, { responseType: "text" }).subscribe(
    data => {
      const htmlStr = this.sanitizer.bypassSecurityTrustHtml(data);
      this.htmlString = eval('`' + htmlStr + '`');
    });
});

.HTML:

 <div  [innerHTML]="htmlString">    </div>

直到上述步骤,它工作正常并且 HTML 按预期呈现,但是 现在,当我尝试使用任何类型的管道时,例如:${this.test | uppercase} 它会出现以下错误:

uppercase is not defined

有什么方法可以达到预期的结果吗?

【问题讨论】:

  • 可以在组件ts文件中使用transform,如constructor(private upperCasePipe: UpperCasePipe) { this.variable = upperCasePipe.transform(this.variable); }
  • @ciekals11 抱歉,我更新了我的问题。我只是想把它作为一个例子来展示,但是当我使用翻译管道时,我没有提供任何特定的变量,所以不可能事先使用转换。
  • 嗯。我认为(还没有测试过)你仍然可以像&lt;th class="border-top-0"&gt;{{ translationPipe.transform('General Kenobi') }}&lt;/th&gt; 一样使用pipeName.transform(),这不是理想的解决方案。但仍然是一个解决方案
  • 对不起。我的意思是${} 而不是{{}}
  • @Vikas 他使用的是${ this.test } 而不是{{ test }},因为它不是您所指的模板,而是包含通过innerHTML 放置在html 中的html 标记的字符串。阅读问题。

标签: javascript html angular template-literals template-strings


【解决方案1】:

嗯。我认为(还没有测试过)你仍然可以使用 pipeName.transform() 像:

<th class="border-top-0">
    ${ this.translationPipe.transform('General Kenobi') }
</th>

这不是理想的解决方案。
但仍然是一个解决方案。

【讨论】:

    猜你喜欢
    • 2022-01-10
    • 2018-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多