在Angular中导入和内联SVG? [英] Importing and inlining SVG in Angular?

查看:476
本文介绍了在Angular中导入和内联SVG?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个SVG圈子:

<svg viewBox="0 0 104 104">
  <circle cx="52" cy="52" r="50" stroke="#003EFF" stroke-width="4" fill="#00FF98" />
</svg>

Angular项目像这样导入它:

import circle from './circle.svg';

并按如下所示将其添加到div元素中:

And adds it to a div element like this:

<div [innerHTML]="svg" style="width:400px"><div>

但是看起来Angular XSS保护正在剥离内容.有没有办法覆盖这个?

But it looks like Angular XSS protection is stripping the content. Is there a way to override this?

我像这样尝试了DomSanitizer:

  constructor(private sanitizer: DomSanitizer) {
    this.trustedCircle = sanitizer.bypassSecurityTrustUrl(this.svg);

但是没有爱.

推荐答案

我使用Angular Material,它很方便:

I use Angular Material, comes in handy with this:

import { MatIconRegistry } from '@angular/material/icon';
import { DomSanitizer } from '@angular/platform-browser';

在构造函数中:

constructor(
    private matIconRegistry: MatIconRegistry,
    private domSanitizer: DomSanitizer
) { }

ngInit中添加图标或图像:

    this.matIconRegistry.addSvgIcon(
        'some-icon',
        this.domSanitizer.bypassSecurityTrustResourceUrl(
            '../img/some-icon.svg'
        )
    );

然后在您的HTML中:

And then in your HTML:

        <mat-icon
            svgIcon="some-icon"
            class="icon-class"
            aria-label="some-icon">
        </mat-icon>

这篇关于在Angular中导入和内联SVG?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆