Importing and inlining SVG in Angular?

2019-09-21 02:10发布

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.

2条回答
乱世女痞
2楼-- · 2019-09-21 02:31

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>
查看更多
成全新的幸福
3楼-- · 2019-09-21 02:53

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);
  }
}
查看更多
登录 后发表回答