我试图向我的 ApexCharts 添加一个新系列(在 ngOnInit 中),但它不断告诉我,我的图表未定义,即使我在构造函数中初始化了它。我选择了“多个系列-组行”图表,您可以在以下链接中找到该图表。 https://apexcharts.com/angular-chart-demos/timeline-charts/multiple-series-group-rows/
@Component({
selector: "app-gantt",
templateUrl: "./gantt.component.html",
styleUrls: ["./gantt.component.css"]
})
export class GanttComponent implements OnInit {
@ViewChild("chart") chart: ChartComponent;
public chartOptions: Partial<ChartOptions>;
constructor() {
this.chartOptions = {
series: [
{
name: "John Adams",
data: [
{
x: "President",
y: [
new Date(1797, 2, 4).getTime(),
new Date(1801, 2, 4).getTime()
]
},
{
x: "Vice President",
y: [
new Date(1789, 3, 21).getTime(),
new Date(1797, 2, 4).getTime()
]
}
]
}
],
chart: {
height: 350,
type: "rangeBar"
},
plotOptions: {
bar: {
horizontal: true,
barHeight: "50%",
rangeBarGroupRows: true
}
},
colors: [
"#1B998B",
"#2E294E",
"#F46036",
"#E2C044"
],
fill: {
type: "solid"
},
xaxis: {
type: "datetime"
},
legend: {
position: "right"
},
tooltip: {
custom: function (opts) {
const fromYear = new Date(opts.y1).getFullYear();
const toYear = new Date(opts.y2).getFullYear();
const values = opts.ctx.rangeBar.getTooltipValues(opts);
return (
'<div class="apexcharts-tooltip-rangebar">' +
'<div> <span class="series-name" style="color: ' +
values.color +
'">' +
(values.seriesName ? values.seriesName : "") +
"</span></div>" +
'<div> <span class="category">' +
values.ylabel +
' </span> <span class="value start-value">' +
fromYear +
'</span> <span class="separator">-</span> <span class="value end-value">' +
toYear +
"</span></div>" +
"</div>"
);
}
}
};
}
ngOnInit() {
this.chart.appendSeries([{
name: "George Washington",
data: [
{
x: "President",
y: [
new Date(1789, 3, 30).getTime(),
new Date(1797, 2, 4).getTime()
]
}
]
}])
}
}
ngOnInit
钩子可能还为时过早,无法使用 @ViewChild
访问元素。它们可能还没有被渲染。你有2个选择
static: true
,以便可以在渲染之前访问变量(仅限 Angular v9+)。请参阅此处了解更多信息。@ViewChild("chart", { static: true }) chart: ChartComponent;
AfterViewInit
挂钩。export class GanttComponent implements AfterViewInit {
@ViewChild("chart") chart: ChartComponent;
...
ngAfterViewInit() {
this.chart.appendSeries([{
...
}]);
}
}
我面临着类似的问题,即使有
AfterViewInit
并等待chart.render()
承诺。
我最终能够在我的 Angular 应用程序中结合使用多种技术来解决这个问题以及其他一些图表渲染问题:
@defer (on viewport)
块内(需要 Angular v17+):@defer (on viewport) {
<apx-chart ... />
} @placeholder {
Loading...
}
这可以防止错误:
Error: <g> attribute transform: Expected number, "translate(NaN, 0) scale(1)".
chartReady
事件。在模板中:
<apx-chart #myChart ... (chartReady)="onChartReady()"/>
在组件中:
@Component({/*...*/})
export class MyComponent {
@ViewChild('myChart', { read: ChartComponent })
protected myChart!: ChartComponent
private _chartReady = false
protected onChartReady() {
this._chartReady = true
this.updateChart()
}
protected updateChart() {
if (!this._chartReady) {
return
}
this.myChart.updateSeries(/*...*/)
}
}