【问题标题】:Access to DOM methods in angular app在 Angular 应用程序中访问 DOM 方法
【发布时间】:2017-12-22 04:11:15
【问题描述】:

我在 Angular 5 应用程序中使用 SVG,我非常依赖访问 DOM 级别的方法,例如:

createSVGPoint();

这是嵌入式 SVG 的样子:

<svg id="mainSVG" no-padding
    viewBox="0 0 480 480"
    preserveAspectRatio="xMidYMid meet"
    width="100%"
    height="100%"
    itemtype="background"
    shape-rendering="auto"
    color-rendering="optimizeSpeed"
    image-rendering="optimizeSpeed"
    xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink"
    ><svg:g id="svgCanvas" transform="matrix(1 0 0 1 0 0)" class="contained" svgcanvas [canvasItemsDataObject]="canvasItemsDataObject" [canvasBackgroundDataObject]="canvasBackgroundDataObject"></svg:g>
</svg>

所以我想我现在的做法很糟糕:

在 ngAfterViewInit() 我调用: this.mainSVG = document.getElementById("mainSVG"); 然后我可以直接使用以下方法对访问方法进行排序:this.mainSVG.createSVGPoint();等等

我知道我不应该直接使用这种方法访问 DOM,但我不知道什么是正确的路径?

我尝试过但未能实现的目标:

  1. 使用 ViewChild: 将 #mainSVG 添加到 html 模板并做了 @ViewChild('mainSVG') mainSVG2: ElementRef;我不能用这个,mainSVG2.createSVGPoint()。

  2. 在 init 函数中执行如下操作: this.mainSVG = this.renderer.selectRootElement('#mainSVG');

还是不适合我;/

什么是访问 SVG 元素的 DOM 级方法的正确方法?

【问题讨论】:

  • 你能分享你的角度代码吗?

标签: angular svg


【解决方案1】:

使用您的方法 #1,您应该能够以这种方式调用 dom 方法

@ViewChild('mainSVG') mainSVG2: ElementRef
//...
mainSVG2.nativeElement.createSVGPoint()

【讨论】:

  • 嘿哟,现在测试一下!
  • 天才!让 x = this.mainSVGViewChild.nativeElement.createSVGPoint(); console.log(x) 工作!那么这是访问 DOM 的更安全的方法吗?
  • 好的,我刚刚将所有的 DOM 访问模式转移到了这种方法。进行得很顺利。对于作为模块的项目,只有一个并发症。但这要归功于此处的另一个线程(必须显式添加才能将这些 ViewChilds 读取为 ElementRef)。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2019-12-25
  • 2018-04-27
  • 2020-02-10
  • 2017-03-31
  • 2021-04-02
  • 2017-11-10
  • 1970-01-01
相关资源
最近更新 更多