Angular中@ViewChild获取SVG元素调用方法报错,getElementById正常是何原因?
问题原因
- @ViewChild 获取到的模板引用变量结果默认是
ElementRef包装对象,不是直接的原生 DOM 节点。你直接在this.pcv上调用isPointInFill相当于在 ElementRef 实例上调用 SVG 元素的专属方法,自然会报方法不存在的错误。 document.getElementById直接返回的是对应 id 的原生SVGPathElement实例,本身就挂载了isPointInFill方法,所以可以正常运行。
修复方案
你只需要从 ElementRef 中取出 nativeElement 属性即可拿到原生 DOM 节点,修改 foo 方法的代码即可:
foo () { // 新增 .nativeElement 取原生节点,注意补充原代码缺失的右括号 console.log(this.pcv.nativeElement.isPointInFill(new DOMPoint(this.px, this.py))); console.log(document.getElementById('ppp').isPointInFill(new DOMPoint(this.px, this.py))); }
如果需要更严谨的类型校验,也可以给 ViewChild 加上类型标注:
import { ElementRef } from '@angular/core'; // ... @ViewChild("ppp") pcv: ElementRef<SVGPathElement>;
内容的提问来源于stack exchange,提问作者chris01
相关产品推荐
相关产品推荐

