My goal is to have an SVG canvas in an Angular 2 template that scales with its parent element and calls a redraw method when its size changes.
Using the onresize property, I get events as expected but I can't call a method of the Component:
<svg width="100%" height="100%" id="canvas" onresize="console.log('resize')">
</svg>
When I use the proper Angular 2 syntax, I can call a method, but the event is never fired:
<svg width="100%" height="100%" id="canvas" (resize)="resize()">
</svg>
To test the logic, I changed (resize) into (click) and then the events are fired when I click on the canvas.
Since this didn't work for me, I tried other ways to attach the onresize event.
First I added #canvas to the svg tag:
<svg width="100%" height="100%" #canvas id="canvas">
</svg>
Then I added a ViewChild to the Component.
@ViewChild('chart') canvas : ElementRef;
I've tried every method as described here: SVGResize | onresize event
function handler() { console.log('SVG resize') }
this.canvas.nativeElement.onresize = handler;
this.canvas.nativeElement.attachEvent("onresize", handler);
this.canvas.nativeElement.addEventListener("SVGResize", handler);
None of them fire any events. The only way so far how I can capture resizes is by setting an event handler at the document level:
window.addEventListener('resize', () => {
this.draw();
});
So whenever the page resizes I can trigger a redraw of the svg. This as a few drawbacks though. First, the SVG does not always resize when the document resizes. Second, the SVG could also resize in other situations when the page remains the same size. I can work around those but it isn't that elegant and prone to bugs. It would be much better just handling the resize on the SVG directly.
As soon as I have time I'm going to make a Plunker. I did my tests using Chrome and Firefox.
Why doesn't the (resize) output work, and how can I properly handle the canvas resize events?
The only way that I could capture resize events directly on the SVG is by using the onresize attribute. Is there a way to call methods of the Component from there?
Rather than capturing resize events, I would implement DoCheck ( https://angular.io/docs/ts/latest/api/core/index/DoCheck-class.html ) and insert an if test for if the canvas scrollWidth/scrollHeight has changed since the last check. This way you can also check if the size has changed even though the page itself hasn't resized.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With