gpt4 book ai didi

angular - bypassSecurityTrustHtml 在使用 [innerHtml] 显示 html 时禁用 anchor 标记

转载 作者:行者123 更新时间:2023-12-05 02:05:14 25 4
gpt4 key购买 nike

我正在使用 Angular 10。我有一个场景可以获取 html 字符串(富文本编辑器返回的值)并将其显示在我的应用程序中(使用 innerHtml )。我将获得各种样式,例如背景颜色、字体颜色、高亮文本、超链接等。

我正在使用 bypassSecurityTrustHtml通过管道(代码在下面)以便 <styles>将考虑标签。

// sanitizeHtml.pipe.ts

@Pipe({ name: 'keepHtml', pure: false })
export class SanitizeHtmlPipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) {
}

transform(content) {
return this.sanitizer.bypassSecurityTrustHtml(content);
}
}

现在的问题是,当我获得超链接文本时 <a href="http://www.someurl.com> click here </a> ,这些 anchor 链接不起作用。因此,当我点击该链接时,它不会打开 href 链接。

我见过类似使用 bypassSecurityTrustResourceUrl 的解决方案.但我无法使用它,因为我无法单独从 html 内容中解析 url。

我还尝试按照其他 SO 问题中的建议使用如下所示的两个函数,但它也无济于事..

[innerHtml]="myHtmlContent | keepHtml | keepUrl"

[innerHtml]="myHtmlContent | keepUrl | keepHtml" // tried to reorder the pipe still didn't work

有没有办法在使用 bypassSecurityTrustHtml 函数时使 anchor 标记的 href 链接起作用?

感谢您的宝贵时间。

最佳答案

经过一些调试后,我发现我们不需要单独清理 html 字符串中的 url。

如果您将管道与 bypassSecurityTrustHtml 一起使用,并且它不能与 anchor 标记链接一起正常工作,那么您可能会犯与我相同的错误。


解决方案

只需从 @Pipe({ name: 'keepHtml', pure: false }) 中删除 pure: false。通过这样做,您的管道将成为纯管道(因为 pure: true 是默认值)

仅当检测到传递给管道的值或参数发生变化时,才会执行纯管道,因为每个变化检测周期都会调用非纯管道。

关于angular - bypassSecurityTrustHtml 在使用 [innerHtml] 显示 html 时禁用 anchor 标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63709051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com