Angular 2 SVG 不渲染 [英] Angular 2 SVG not rendering

查看:55
本文介绍了Angular 2 SVG 不渲染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个组件来渲染我应用中的 SVG 图像.

动态加载,然而,我的演示应用程序只显示一个更简单的版本.

http://plnkr.co/edit/g2tZXeUAMJ5zESx2EHT0?p=info

我尝试了 <div [innerHTML]="data"></div><div>{{数据}}

尽管调用正确,但未加载 SVG.我花了一些时间在 gitter 中寻找解决方案,但我得到的最接近的是它正在被清理.

我假设的innerHTML 正在被清理并且插值被忽略.它只显示原始 svg 文本.

谢谢

解决方案

Angular 正在清理内容.要解决此问题,请明确告诉 Angular 它可以信任您的 HTML

从'@angular/core'导入{管道,消毒剂};

您可以使用可重复使用的管道或直接调用 sanitizer.bypassSecurityTrustHtml(html).

@Pipe({name: 'safe'})导出类 SafeHtml {构造函数(私有消毒剂:DomSanitizer){}变换(html){返回 this.sanitizer.bypassSecurityTrustHtml(html);}}

并像使用它一样

[innerHTML]="数据 |安全"

Plunker 示例

另见 在RC.1 某些样式无法使用绑定语法添加

I created a component to render SVG images that are within my app.

The are loaded dynamically as the however, my demo app just show a simpler version.

http://plnkr.co/edit/g2tZXeUAMJ5zESx2EHT0?p=info

i tried <div [innerHTML]="data"></div> and <div> {{ data }} </div>

The SVG is not being loaded though the call is correct. I spent sometime in gitter to find a solution but the closest i got was it it's being sanitzed.

The innerHTML i assume is being sanitzed and the interpolation is being ignored. It just shows the raw svg text.

Thanks

解决方案

Angular is sanitizing the content. To work around explicitly tell Angular that it can trust your HTML

import { Pipe, Sanitizer } from '@angular/core';

You can use a reusable pipe or call sanitizer.bypassSecurityTrustHtml(html) directly.

@Pipe({name: 'safe'})
export class SafeHtml {
  constructor(private sanitizer:DomSanitizer){}

  transform(html) {
    return this.sanitizer.bypassSecurityTrustHtml(html);
  }
}

and use it like

[innerHTML]="data | safe"

Plunker example

See also In RC.1 some styles can't be added using binding syntax

这篇关于Angular 2 SVG 不渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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