简体   繁体   English

使用 Angular 中的 Renderer2 渲染 SVG

[英]Rendering SVGs using Renderer2 in Angular

How do I render an SVG (which I have locally stored in my project) using Renderer2 in Angular?如何使用 Angular 中的 Renderer2 渲染SVG (我已本地存储在我的项目中)?

I tried doing it like following:我尝试这样做:

const div = this.renderer.createElement('div');
const svg = this.renderer.createText('<svg>{....}</svg>');
this.renderer.appendChild(div, svg);

But it actually got renderer as a text.但它实际上将渲染器作为文本。

Can someone help?有人可以帮忙吗?

The createText method is used to create a text node , in this case you can set innerHTML directly. createText方法用于创建文本节点,此时可以直接设置innerHTML。

const div = this.renderer.createElement('div');
div.innerHTML = svgStr;

Remember that you can create a svg with a selected path using a simple variable and [attr.d]="variable in a path, eg请记住,您可以使用简单变量和路径中的[attr.d]="variable创建具有选定路径的 svg,例如

<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" 
      fill="currentColor" viewBox="0 0 16 16">
  <path [attr.d]="path"/>
</svg>

And in.ts:和 in.ts:

path="M14 16a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2H2a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12zM5.904 5.197 10 9.293V6.525a.5.5 0 0 1 1 0V10.5a.5.5 0 0 1-.5.5H6.525a.5.5 0 0 1 0-1h2.768L5.197 5.904a.5.5 0 0 1 .707-.707z"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM