首页 > 解决方案 > 以角度 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) ;
    } 

  }

标签: angulardomsvg

解决方案


您遇到的问题与您使用的对象元素有关,该元素用于管理外部资源并创建“子窗口”(如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);
    });
  }
}

推荐阅读