我想要显示保存在ts文件数组中的SVG图标,在模板中,但InnerHTML似乎不起作用,我如何修复它?

export class SidenavComponent {
  sideBarIcons: IInstagramIcons[] = [
    {
      name: 'Home',
      svgPath: '<svg aria-label="Home" class="x1lliihq x1n2onr6 x5n08af" fill="currentColor" height="24" role="img" viewBox="0 0 24 24" width="24"><title>Home</title><path d="M9.005 16.545a2.997 2.997 0 0 1 2.997-2.997A2.997 2.997 0 0 1 15 16.545V22h7V11.543L12 2 2 11.543V22h7.005Z" fill="none" stroke="currentColor" stroke-linejoin="round" stroke-width="2"></path></svg>'
    },
    {
      name: 'Search',
      svgPath: `<svg aria-label="Search" class="x1lliihq x1n2onr6 x5n08af" fill="currentColor" height="24" role="img" viewBox="0 0 24 24" width="24"><title>Search</title><path d="M19 10.5A8.5 8.5 0 1 1 10.5 2a8.5 8.5 0 0 1 8.5 8.5Z" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"></path><line fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" x1="16.511" x2="22" y1="16.511" y2="22"></line></svg>`
    },
  ]
}








<nav class="vertical-sidenav-left bg-black w-80 p-10">
  <div class="text-white">
    <ul>
      <!--get svg paths from the ts file array-->
      @for (icon of sideBarIcons; track icon.name){
        <div>{{icon.name}}</div>
        <div [innerHTML]="icon.svgPath"></div>
      }

    </ul>
  </div>
</nav>

推荐答案

  1. 导入DomSaniizer:

    import { DomSanitizer } from '@angular/platform-browser';
    
  2. 将其放入构造函数中:

     public sanitizer: DomSanitizer
    
  3. 并将您的innerHtml行更改为:

    <div [innerHtml]="sanitizer.bypassSecurityTrustHtml(icon.svgPath)"></div>.
    

Angular相关问答推荐

如何取回.angular/ache文件夹?

HttpInterceptorFn在Angular 17中被忽略

如何通过innerHtml在模板中显示动态插入的动感图标?

在RxJS和ANGING中处理多个API调用

成Angular 的嵌套router-outlet

如何在Primeng中实现自定义排序

RXJS拆分返回值,多次调用后重新加入

使用 Angular 类构造函数来获取依赖项

使用 primeng Apollo 主题进行实时部署时多次加载 theme.css 和 preloading.css 文件

npm install命令在基本Angular 应用程序的天蓝色构建管道中失败

在switchMap操作符中使用条件语句以进行第一次或随后的执行

RxJs 中的空闲可观察对象在幕后做了什么?

如何在 Angular 2 中获取与 ElementRef 关联的组件的引用

如何在 Angular Cli 中生成 .angular-cli.json 文件?

Angular 5 Mat-grid 列表响应式

如何在 Angular 2 中正确设置 Http 请求标头

Angular @NGRX中这三个点的含义是什么

默认情况下如何在Angular中 Select mat-button-toggle

Firestore 从集合中获取文档 ID

缺少带有Angular的语言环境XXX的语言环境数据