如何使用 Angular TypeScript 添加 SVGelement

How to add SVGelement with Angular TypeScript

我有一个 Angular 服务 returns SVGElements,我想将它们包含在模板中,但我无法将它们插入模板。我确信这是一件很常见的事情,但我所有的谷歌搜索和 RTFM'ing 都让我失望了。

这是一个最小的例子(当然是在调用 ng init 之后):

[app.component.html]
<h1>
  {{title}}
  <div [innerHTML]="circle"></div>
  <div [innerHTML]=circle.outerHTML></div>
  <div >{{circle}}</div>
  <div >{{circle.outerHTML}}</div>
</h1>

[app.componoent.ts]
import { Component } from '@angular/core';

// create an SVGElement
var svg_string  = '<svg xmlns="http://www.w3.org/2000/svg" height="100" width="100"> <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" /> </svg>'
var parser = new DOMParser();
var circle_elt = parser.parseFromString(svg_string, "image/svg+xml").childNodes[0];

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app works!';
  circle = circle_elt;
}

我得到的是一个显示文本的网页:

app works!
[object SVGSVGElement]
[object SVGSVGElement]
<svg xmlns="http://www.w3.org/2000/svg" height="100" width="100"> <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red"/> </svg>

并且在控制台中,有消息指出:

"WARNING: sanitizing HTML stripped some content (see http://g.co/ng/security#xss)."

您需要使用消毒剂:

constructor(private sanitizer:DomSanitizer){}

var circle_elt = this.sanitizer.bypassSecurityTrustHtml(
    parser.parseFromString(svg_string, "image/svg+xml").childNodes[0]
);

另见