我正在寻找一种方法来显示页面上的文本(markdown ),可以包含一个讨人喜欢的图标.框架的Angular 是15,并使用了可怕的6.

文本通过innerHTML标签动态插入. 通过一个标记管道,我能够将文本(以标记形式)转换为语义正确的HTML.不幸的是,关于图标的解析,我目前还没有找到一个好的解决方案.我不明白的是,我如何防止ng/security#xss清理我的代码,同时让图标占位符转换以调用并显示有趣的组件?

我try 使用

content.replace(/{!!icon!!}/g, '<fa-icon [icon]="faCoffee"></fa-icon>')

以用图标替换占位符{!!icon!!}.然而,Angular的安全干预并杀死了<fa-icon [icon]="faCoffee"></fa-icon>.所以我try 在管道中使用return this.domSanitizer.bypassSecurityTrustHtml来防止ng/security#xss杀死我的代码.这是可行的,但图标不显示,因为代码<fa-icon [icon]="faCoffee"></fa-icon>没有被解释.

@Pipe({
  name: 'sanitizer'
})
export class SanitizerPipe implements PipeTransform {

  constructor(private domSanitizer: DomSanitizer) { }

  transform(content: string, ...args: unknown[]): unknown {
      return this.domSanitizer.bypassSecurityTrustHtml(this.iconParser(content)) as SafeHtml;
    }
  }

  private iconParser = (content: string) => {
    return content.replace(/{!!icon!!}/g, `<fa-icon [icon]="faCoffee"></fa-icon>`);
  }

}

很久以前,我看到一个question被问到,他们已经通过注入Fontawous组件解决了问题.所以我的方法很容易出错,但我不知道如何用这个来解决它.

Angel不必要地复杂的"文档"(API),像往常一样对这个主题只字不提.

推荐答案

这个特殊的问题由Fontawesome通过this guide直接解决.库(angular-fontawesome)提供函数icon().这解决了问题,因为你只需要做:

import { icon } from '@fortawesome/fontawesome-svg-core';

...

private iconParser = (content: string) => {
  return content.replace(/{!!icon!!}/g, `${icon(faCoffee).html.join('')}`);
}

icon(faCoffee).html.join('')代码生成一个有效的SVG:

<svg aria-hidden="true" focusable="false" ... ><path fill="currentColor" ...></path></svg>

Angular相关问答推荐

Angular:浏览器中未显示一些Google Content图标

在Angular 17中加载页面时打开打印对话框

嵌套formArrays的HTML迭代

Angular 17自定义指令渲染不起作用'

尽管有模拟间谍实现,规范文件仍调用真正的服务

Angular 17:在MouseOver事件上 Select 子组件的正确ElementRef

Angular 单调服务已多次创建

无法绑定到formControl,因为它不是input的已知属性

VSCode / Angular 应用程序未完全启动

Angular:如何设置 PrimeNG p-steps 组件中已完成步骤的样式?

如果Angular 数据为空,如何设置N/A

Angular:为什么在我的自定义 ErrorHandler 中订阅主题不触发?

如何处理Angular 延迟订阅

将 html ngModel 值传递给服务 --Angular

Angular 2如何使用路由和location.go()检测后退按钮按下?

*ngIf 和 *ngFor 在 元素上使用

相对于根目录的 SCSS 导入

样式 html,来自 Web 组件的正文

Angular 中 polyfills.ts 文件有什么用

使用 EventEmitter 传递参数