Importing and inlining SVG in Angular?

自作多情 提交于 2020-01-07 07:57:25

问题


This is an SVG Circle:

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

This Angular Project imports it like this:

import circle from './circle.svg';

And adds it to a div element like this:

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

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

I tried the DomSanitizer like this:

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

But no love.


回答1:


I use Angular Material, comes in handy with this:

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

In the constructor:

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

Add the icon or image in ngInit:

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

And then in your HTML:

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



回答2:


Just fix it for you. You can try to see if it work

import { Component } from '@angular/core';
import { DomSanitizer
} from '@angular/platform-browser';
import circle from './circle.svg';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  trustedCircle;
  constructor(private sanitizer: DomSanitizer) {
    this.trustedCircle = this.sanitizer.bypassSecurityTrustHtml(circle);
  }
}


来源:https://stackoverflow.com/questions/57642008/importing-and-inlining-svg-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!