In my ionic3 program, there is an error Unhandled Promise rejection: Cannot read properties of null (reading 'setAttribute') ; Zone: <root> ; Task: Promise.then ; Value: TypeError: Cannot read properties of null (reading 'setAttribute')
Source code is:
.ts
...
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;
}
CodePudding user response:
Seems like you're trying to apply operations on DOM before it gets rendered. To achieve the same, you can put your code inside ngAfterViewInit
lifecycle hook, which makes sure the DOM is ready/rendered before you modify it.
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);
}
Note:- Won't recommend to do direct DOM operations inside angular, please read Working with DOM in Angular: unexpected consequences