在双花括号内呈现HTML

时间:2019-02-14 19:10:39

标签: angular angular-template angular-pipe

我在Ionic / Angular应用程序中使用管道,该管道正在转换文本并返回带有html代码的结果。

这是我如何使用管道的示例:

<ion-label>
  <span>{{ text | mypipe: 'lo':'secondary' }}</span>
</ion-label>

两次卷曲中得到的代码HTML如下:

Loth<ion-text color='secondary'>lo</ion-text>rien

问题是执行后,我在标签中看到的全部是Loth<ion-text color='secondary'>lo</ion-text>rien而不是Loth lo rien,其中带有文本的彩色部分(即:“ lo”)< / p>

有人知道我为什么有这种行为以及如何解决它吗?

谢谢

1 个答案:

答案 0 :(得分:1)

TLDR

当您要渲染包含角度分量的html时,必须创建/编译它们dynamically in runtime

默认情况下,Angular会清除视图中的所有内容。要在模板中显示html,您必须使用:

<span [innerHTML]="text | mypipe: 'lo':'secondary'"></span>

您的管道应返回SafeHtml

@Pipe({
    name: 'mypipe'
})
export class MyPipe implements PipeTransform {

    constructor(private sanitizer: DomSanitizer) {}

    public transform(value, params): SafeHtml {
        //do whatever your pipe does and then
        return this.sanitizer.bypassSecurityTrustHtml(somethingToReturn);
    }
}

请参见this question

您还可以像在this article中那样编写通用管道,然后直接使用它:

<span [innerHTML]="text | mypipe: 'lo':'secondary' | safe: 'html'"></span>

但是由于您的标记包含另一个角度分量,因此它将无法工作。它可以与标准html标记一起使用。 您想寻找一种方法,该方法不仅可以动态渲染某些html,还可以动态compile来动态创建模板并动态创建生成的组件。 these lines周围的东西。

相关问题