我使用 D3 餅圖創建了一個甜甜圈,并在我的 angular (12) 應用程式中添加了一些影片。當我第一次加載頁面時,我制作的圖表作業正常(這是登錄后加載的頁面)。然后,如果我轉到另一個頁面,并以任何方式回傳(來自瀏覽器或路由的上一頁),餅圖首先出現然后完全消失,svg 元素不再在 DOM 中。
例如,在第一次加載時,我的 DOM 中有這個 svg :
<svg width="80" height="80">
<g transform="translate(40, 40)" id="g-7621300556">
<linearGradient x1="0" x2="1" y1="1" y2="0.5" id="gradient-url-7621300556">
<stop offset="0%" stop-color="var(--secondary)" stop-opacity="0.1"></stop>
<stop offset="100%" stop-color="var(--secondary)" stop-opacity="1"></stop>
</linearGradient>
<path fill="url(#gradient-url-7621300556)" d="M-5.970153145843346e-15,32.5A32.5,32.5,0,0,1,-30.90933677959249,-10.043052317185793L-26.15405419811672,-8.497967345311057A27.5,27.5,0,0,0,-5.051668046482832e-15,27.5Z" style="transform: rotate(180deg)" opacity="0.3" stroke=""></path>
<path fill="transparent" d="M-30.90933677959249,-10.043052317185793A32.5,32.5,0,1,1,1.990051048614449e-15,32.5L1.6838893488276107e-15,27.5A27.5,27.5,0,1,0,-26.15405419811672,-8.497967345311057Z" style="transform: rotate(180deg)" opacity="1" stroke="var(--background)"></path>
<text text-anchor="middle" dy=".3em" id="text-7621300556" fill="var(--secondary)">30 %</text>
</g>
</svg>
然后什么都沒有,根本沒有svg。我做了這個 gif 來說明:

這是我所做的:
chart.component.ts:
import { Component, Input, AfterViewInit, OnChanges, SimpleChanges } from '@angular/core';
import * as d3 from 'd3';
export class ChartDataSet {
filledPartPercent: number;
emptyPartPercent: number;
label?: string;
}
@Component({
selector: 'chart',
templateUrl: './chart.component.html',
styleUrls: ['./chart.component.scss'],
})
export class ChartComponent implements AfterViewInit, OnChanges {
@Input() donutId: string;
@Input() dataSet: ChartDataSet;
@Input() width: number;
@Input() margin: number;
@Input() duration = 1500;
@Input() thickness = 2.5;
@Input() anglesRange = Math.PI;
@Input() cssVarColor = 'var(--secondary)';
@Input() gradient = false;
height: number;
radius: number;
svg: any;
randomize: number;
constructor() {
}
ngAfterViewInit() {
this.init();
}
ngOnChanges(changes: SimpleChanges): void {
this.init();
}
private init(): void {
this.randomize = Math.floor(Math.random() * (10000 - 10) 10);
this.height = this.width;
this.radius = (this.width / 2) - this.margin;
this.donutDraw();
}
private donutDraw() {
const percent = this.dataSet.filledPartPercent;
const color = this.cssVarColor;
const id = this.donutId;
const random = this.randomize;
let gradientElement = null;
const data = {
lower: this.calcPercent(0),
upper: this.calcPercent(percent)
};
const arc = d3.arc().innerRadius(this.radius - this.thickness).outerRadius(this.radius this.thickness);
const pie = d3.pie().value(d => d).sort(null).startAngle(this.anglesRange * -1).endAngle(this.anglesRange);
this.svg = d3.select('#donut-' id).append('svg')
.attr('width', this.width)
.attr('height', this.height)
.append('g')
.attr('transform', 'translate(' this.width / 2 ', ' this.height / 2 ')')
.attr('id', 'g-' id random);
if (this.gradient) {
gradientElement = this.svg.append('linearGradient').attr('x1', '0').attr('x2', '1').attr('y1', '1').attr('y2', '0.5')
.attr('id', 'gradient-url-' id random);
gradientElement.append('stop').attr('offset', '0%').attr('stop-color', color).attr('stop-opacity', '0.1');
gradientElement.append('stop').attr('offset', '100%').attr('stop-color', color).attr('stop-opacity', '1');
}
let path = this.svg.selectAll('path')
.data(pie(data.lower))
.enter().append('path')
.attr('fill', 'var(--background')
.attr('d', arc)
.each(function(d) { this._current = d; });
const text = this.svg.append('text').attr('text-anchor', 'middle').attr('dy', '.3em')
.attr('id', 'text-' id random);
const timeout = setTimeout(() => {
clearTimeout(timeout);
path = path.data(pie(data.upper));
path.transition()
.duration(this.duration)
.attrTween('d', function(a, index) {
const self = this;
const i = d3.interpolate(this._current, a);
const i2 = d3.interpolateNumber(0, percent);
this._current = i(0);
return t => {
d3.select(self).attr('fill', index !== 0 ? 'transparent' : gradientElement != null ? 'url(#gradient-url-' id random ')' : color )
.attr('style', 'transform: rotate(180deg)')
.attr('opacity', index !== 0 ? 1 : i2(t) / 100)
.attr('stroke', index !== 0 ? 'var(--background)' : '');
text.text(Math.round(i2(t)) ' %').attr('fill', color);
return arc(i(t));
};
});
});
}
private calcPercent(percent) {
return [percent, 100 - percent];
}
}
圖表.component.html
<div [id]="'donut-' donutId" class="wrap"></div>
圖表組件.scss
.wrap {
width: 100%;
height: 100%;
display: block;
}
我嘗試了一些基于其他 SO 頁面的方法,例如this one,但到目前為止沒有任何效果。我的圖表有一個隨機生成的id,漸變也是如此,我不知道下一步該怎么做。我也嘗試在Stackblitz上重現它,但它作業正常......
我不知道是什么原因造成的,如果您需要更多代碼,請告訴我。
uj5u.com熱心網友回復:
正如評論中所建議的,問題通常不是 D3.js 或 SVG,而是與此問題有關。
就我而言,我在 ngFor 上缺少 trackBy 函式,這導致多次重新加載組件。
更正它解決了我的問題,但并沒有完全解釋為什么它消失而不僅僅是重新加載。我發現我遺漏了幾件事來正確地完成它,一句話:NgOnDestroy。
我將此添加到我的代碼中,以便在重新加載時它不會消失:
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();
}
[......]
}
如果有人遇到此類問題,我希望這會有所幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/367898.html
