angular - 以角度 6 访问 dom 元素
问题描述
在一个组件中,我在模板中有一个 svg 渲染,并会对其进行操作以放置一些图形。实际上,我无法使用 nativeElement 或 HTMLElement 访问 svg 文档。
模板是:
template:
`<div>
<object data="/assets/deploiement.svg" type="image/svg+xml" height="450" width="650" #dataSvg >
</object>
</div>`,
我想实现的例子:
ngAfterViewInit() {
const elemnentRef = this.dataSvg;
console.log(elemnentRef.);
const circle = '<circle cx="500" cy="50" r="65" />';
( this.state === 2 ) {
this.dataSvg.nativeElement.svg.append(circle) ;
}
}
解决方案
您遇到的问题与您使用的对象元素有关,该元素用于管理外部资源并创建“子窗口”(如iframe一样)。
因此,如果您真的想保留这种方法,您必须操作加载的内容的唯一方法<option>
是等待内容加载并<svg>
在子窗口内定位元素。
请注意,由于CORS限制,这仅在您加载的内容来自与您的页面相同的服务器时才有效。
这是一个演示解决方案的简单 Stackblitz 示例。
import { AfterViewInit, Component, ElementRef, ViewChild } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<div>
<object data="/assets/debug.svg" type="image/svg+xml" height="450" width="650" #dataSvg></object>
</div>
`,
})
export class AppComponent implements AfterViewInit {
@ViewChild('dataSvg') dataSvg: ElementRef;
ngAfterViewInit() {
const elemnentRef = this.dataSvg;
// when content is loaded...
elemnentRef.nativeElement.contentWindow.addEventListener('load', function (event) {
// ...retrieve svg element
const document = elemnentRef.nativeElement.contentWindow.document;
const svg = document.querySelector('svg');
// create a circle
const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
circle.setAttributeNS(null, 'cx', 50);
circle.setAttributeNS(null, 'cy', 50);
circle.setAttributeNS(null, 'r', 40);
circle.setAttributeNS(null, 'fill', 'red');
// append it to existing content
svg.append(circle);
});
}
}
推荐阅读
- encryption - ACS ACR 1255U-J1 NFC 阅读器 - 如何开始自动轮询
- java - 如何从Java中的元组列表中提取第n个元素?
- javascript - 如何在wordpress中通过ajax发布音频blob?
- sharepoint - SharePoint Online:取消要求必填字段
- java - spring bean范围用例和性能差异
- typescript - 打字稿的自定义错误,类型问题:与类型没有共同的属性
- ssh - SSHPASS 未将密码传递给 SUDO 命令
- vue.js - 有没有办法在组路由中重定向路由?
- powershell - Powershell - 从另一个脚本块的 AST 创建动态参数
- reactjs - 使用 github pages 部署时 React App Blank 的第一页