score:0

Accepted answer

As suggested in comments, the problem wasn't D3.js or SVG in general, but related to this issue.

In my case, I was missing a trackBy function on a ngFor, which was leading to reload components several times.

Correcting it fixed my issue, but didn't totally explain why it was disappearing and not just reloading. I found out that I was missing few things to do it properly, in one word : NgOnDestroy.

I added this to my code, so that it won't disappear if reloaded :

export class ChartComponent implements AfterViewInit, OnChanges, OnDestroy {
    @ViewChild('donutRef', { static: true}) donutRef: ElementRef; // <--- top div of this component
    [......]
    svg: any; // <--- this.svg = d3.select('#donut-' + id).append('svg') when initialising the chart
    [......]

    public ngOnDestroy() {
        this.svg.remove();
        this.donutRef.nativeElement.remove();
    }
    [......]
}

I hope this can help if anyone encouters this kind of issue.


Related Query

More Query from same tag