Angular框架中ApexCharts缩小窗口时图表偏移至卡片内部异常
解决方案
问题根源为ApexCharts甜甜圈图在父容器尺寸变化时未触发自动重绘,弹性容器对齐规则与图表默认配置冲突导致偏移,按以下步骤修改即可修复:
1. 调整业务组件TS代码
补充图表实例引用,增加窗口变化时的重绘逻辑,完善图表配置项:
import { Component, OnInit, ViewChild, OnDestroy } from '@angular/core'; import { ApexChartComponent, ChartType } from 'ng-apexcharts'; @Component({ selector: 'app-dashboard', templateUrl: './dashboard.component.html' }) export class DashboardComponent implements OnInit, OnDestroy{ @ViewChild(ApexChartComponent) private chartInstance: ApexChartComponent; riskByCategoryAnalysis: ChartType; // 防抖计时器 private resizeTimer = null; constructor(){} ngOnInit(){ this.processRiskByCategory(); // 监听窗口大小变化,防抖触发图表重绘 window.addEventListener('resize', this.handleResize); } private processRiskByCategory() { this.riskByCategoryAnalysis = { series: [this.one, this.two, this.three, this.four], chart: { height: 276, type: 'donut', width: '100%', // 开启自动调整尺寸 autoResize: true }, labels: ["One", "Two", "Three", "Four"], plotOptions: { pie: { // 强制图表无偏移 offsetX: 0, offsetY: 0, donut: { size: '75%' } } }, dataLabels: { enabled: false }, legend: { show: false, }, colors: ['#0090E7', '#99D3F5', '#1BC59C', '#A4E8D7'], }; } private handleResize = () => { if (this.resizeTimer) clearTimeout(this.resizeTimer); this.resizeTimer = setTimeout(() => { this.chartInstance?.updateOptions(this.riskByCategoryAnalysis, true, true, true); }, 200); } // 组件销毁时移除监听避免内存泄漏 ngOnDestroy() { window.removeEventListener('resize', this.handleResize); if (this.resizeTimer) clearTimeout(this.resizeTimer); } }
2. 调整组件模板代码
固定父容器高度,给图表组件指定宽高适配规则:
<div class="row" id="apex-chart"> <div class="col-md-7 d-flex align-items-center justify-content-center pr-0" style="height: 276px;width:100%;"> <apx-chart dir="ltr" class="apex-charts" *ngIf="riskByCategoryAnalysis" style="width: 100%;height:100%;" [series]="riskByCategoryAnalysis.series" [chart]="riskByCategoryAnalysis.chart" [legend]="riskByCategoryAnalysis.legend" [colors]="riskByCategoryAnalysis.colors" [labels]="riskByCategoryAnalysis.labels" [dataLabels]="riskByCategoryAnalysis.dataLabels" [plotOptions]="riskByCategoryAnalysis.plotOptions"> </apx-chart> </div> </div>
3. 补充全局样式(可选)
如果仍有偏移问题,可在全局样式表中添加以下规则强制图表适配容器:
.apex-charts { width: 100% !important; height: 100% !important; } .apex-charts svg { width: 100% !important; height: 100% !important; }
内容的提问来源于stack exchange,提问作者vidya
相关产品推荐
相关产品推荐

