Ionic 无法读取null的属性(阅读'setAttribute')

arknldoa  于 2022-12-08  发布在  Ionic
关注(0)|答案(1)|浏览(272)

在我的ionic3程序中,有一个错误Unhandled Promise rejection: Cannot read properties of null (reading 'setAttribute') ; Zone: <root> ; Task: Promise.then ; Value: TypeError: Cannot read properties of null (reading 'setAttribute')
源代码为:
文件

... 
d = [
    "M", start.x, start.y,
    "A", opts.radius, opts.radius, 0, largeArcFlag, 0, end.x, end.y,
    "L", opts.cx, opts.cy,
    "Z",

    "M", start2.x, start2.y,
    "A", cutout_radius, cutout_radius, 0, largeArcFlag, 0, end2.x, end2.y,
    "L", opts.cx, opts.cy,
    "Z"
  ].join(" ");
document.getElementById('red').setAttribute("d", d);

.html格式

<svg viewBox="0 200 400 400" width="400" height="400">
  <path id="red" fill="red" stroke="none" fill-rule="evenodd" />
</svg>

.scss格式

svg {
  background: #ddd;
  display:block;
  margin-top: 2rem;
}
h9a6wy2h

h9a6wy2h1#

看起来你试图在DOM被呈现之前对其进行操作。为了实现同样的目的,你可以将你的代码放在ngAfterViewInit生命周期钩子内,这可以确保在你修改DOM之前它已经准备好/呈现了。

ngAfterViewInit() {
  const d = [
    "M", start.x, start.y,
    "A", opts.radius, opts.radius, 0, largeArcFlag, 0, end.x, end.y,
    "L", opts.cx, opts.cy,
    "Z",

    "M", start2.x, start2.y,
    "A", cutout_radius, cutout_radius, 0, largeArcFlag, 0, end2.x, end2.y,
    "L", opts.cx, opts.cy,
    "Z"
  ].join(" ");
  document.getElementById('red').setAttribute("d", d);
}

注意:-不建议在Angular 内直接执行DOM操作,请阅读Working with DOM in Angular: unexpected consequences

相关问题