Angular:动态渲染时 SVG 路径标签不可见

如何解决Angular:动态渲染时 SVG 路径标签不可见

我有一个从服务器获取的 SVG 文件,然后我必须将其渲染到我拥有的视图中。

问题是我不能使用 <img>[innerHTML],因为我需要添加用户交互和事件并将其集成到 Angular 的生命周期中。

所以我编写了以下代码来解析 XML 并将其呈现为组件模板中的具体元素:

svg-map-test.component.ts:

import { AfterViewChecked,AfterViewInit,ChangeDetectorRef,Component,Inject,OnInit } from '@angular/core';
import { DOCUMENT } from '@angular/common';

const svg = `
<!-- Generator: Adobe Illustrator 24.0.2,SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 1180.5 841.9" style="enable-background:new 0 0 1180.5 841.9;" xml:space="preserve">
<style type="text/css">
\t.st0{fill:#F89464;}
\t.st1{fill:#B6B773;}
\t.st2{fill:#4CFEFC;}
\t.st3{fill:#606060;}
\t.st4{fill:#FFFFFF;}
</style>
<g id="s:gold">
\t<g id="r:a">
\t\t<g id="c:a2">
\t\t\t<path class="st0" d="M911.9,62.3H896c-2.1,0-3.8-1.7-3.8-3.8V42.6c0-2.1,1.7-3.8,3.8-3.8h15.9c2.1,3.8,1.7,3.8v15.9
\t\t\t\tC915.7,60.6,914,62.3,911.9,62.3z"/>
\t\t</g>
\t</g>
</g>
</svg>
`


@Component({
  selector: 'app-svg-map-test',templateUrl: './svg-map-test.component.html',styleUrls: ['./svg-map-test.component.scss']
})
export class SvgMapTestComponent implements OnInit,AfterViewChecked {

  xmlDom: Document;

  constructor(@Inject(DOCUMENT) private document: Document,private cdRef: ChangeDetectorRef) {
  }

  ngOnInit(): void {
    const parser = new DOMParser();
    this.xmlDom = parser.parseFromString(svg,'image/svg+xml');
  }

  fakeArray(collection: HTMLCollection) {
    const res = [];
    for (let i = 0; i < collection.length; i++) {
      res.push(collection.item(i));
    }
    return res;
  }

}

svg-map-test.component.html:

<ng-container *ngIf="xmlDom" [ngTemplateOutlet]="element" [ngTemplateOutletContext]="{ $implicit: xmlDom.documentElement }"></ng-container>

<ng-template #element let-parent>
  <ng-container [ngSwitch]="parent.nodeName">
    <ng-container *ngSwitchCase="'svg'" [ngTemplateOutlet]="svgElement" [ngTemplateOutletContext]="{ $implicit: parent }">
    </ng-container>
    <ng-container *ngSwitchCase="'style'" [ngTemplateOutlet]="styleElement" [ngTemplateOutletContext]="{ $implicit: parent }">
    </ng-container>
    <ng-container *ngSwitchCase="'g'" [ngTemplateOutlet]="gElement" [ngTemplateOutletContext]="{ $implicit: parent }">
    </ng-container>
    <ng-container *ngSwitchCase="'rect'" [ngTemplateOutlet]="rectElement" [ngTemplateOutletContext]="{ $implicit: parent }">
    </ng-container>
    <ng-container *ngSwitchCase="'path'" [ngTemplateOutlet]="pathElement" [ngTemplateOutletContext]="{ $implicit: parent }">
    </ng-container>
  </ng-container>
</ng-template>

<ng-template #nested let-children>
  <ng-container *ngFor="let item of fakeArray(children)">
    <ng-container [ngTemplateOutlet]="element" [ngTemplateOutletContext]="{ $implicit: item }"></ng-container>
  </ng-container>
</ng-template>

<ng-template #svgElement let-svg>
  <svg [attr.version]="svg.getAttribute('version')"
       [attr.xmlns]="svg.getAttribute('xmlns')"
       [attr.xmlns:xlink]="svg.getAttribute('xmlns:xlink')"
       [attr.x]="svg.getAttribute('x')"
       [attr.y]="svg.getAttribute('y')"
       [attr.viewBox]="svg.getAttribute('viewBox')"
       [attr.xml:space]="svg.getAttribute('xml:space')">
    <ng-container [ngTemplateOutlet]="nested" [ngTemplateOutletContext]="{ $implicit: svg.children }"></ng-container>
  </svg>
</ng-template>

<ng-template #styleElement let-style>
  <style type="text/css">
    .st0{fill:#F89464;}
    .st1{fill:#B6B773;}
    .st2{fill:#4CFEFC;}
    .st3{fill:#606060;}
    .st4{fill:#FFFFFF;}
  </style>
</ng-template>

<ng-template #gElement let-g>
  <g [attr.id]="g.getAttribute('id')">
    <ng-container [ngTemplateOutlet]="nested" [ngTemplateOutletContext]="{ $implicit: g.children }"></ng-container>
  </g>
</ng-template>

<ng-template #rectElement let-rect>
  <rect [attr.x]="rect.getAttribute('x')"
        [attr.y]="rect.getAttribute('y')"
        [class]="rect.className"
        [attr.width]="rect.getAttribute('width')"
        [attr.height]="rect.getAttribute('height')"></rect>
</ng-template>

<ng-template #pathElement let-path>
  <path [attr.d]="path.getAttribute('d')">
  </path>
</ng-template>

但是,没有显示任何内容。 现在,当我在浏览器中检查 DOM 时,一切都在那里并正确呈现,但我注意到 d 属性没有反映在元素样式中,如下例所示:

enter image description here

我尝试在 detectChanges 中使用 ngAfterViewInit,但是没有用。 当我弄乱检查器并在 SVG 中手动添加一个随机 <g> 时,所有内容突然变得可见,并且 d 属性正确反映在相应元素的样式中。

注意:如果您认为有更好的方法来实现我想要做的事情,请告诉我。

解决方法

显然这是 Angular 中长期存在的错误。

https://github.com/angular/angular/issues/41308

编辑:我发现您可以通过用自己的 SVG 标签围绕 ng-template 中使用的 SVG 的每个子元素来缓解这个问题。它没有明显的缺点。

<ng-template #rectElement let-rect>
  <svg>
    <rect [attr.x]="rect.getAttribute('x')"
          [attr.y]="rect.getAttribute('y')"
          [class]="rect.className"
          [attr.width]="rect.getAttribute('width')"
          [attr.height]="rect.getAttribute('height')"></rect>
  </svg>
</ng-template>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-