Angular15+Bootstrap5模态框中ApexCharts不显示问题求助
问题:模态框内ApexCharts无法正常渲染
在Angular 15 + Bootstrap 5项目中使用ApexCharts时遇到以下异常:
- 打开模态框后图表完全不显示
- 仅在页面刷新后将浏览器缩放至90%/100%时图表临时显示,但刷新页面后再次消失
- 图表放置在模态框外时可正常渲染
解决方案
核心原因是模态框初始处于隐藏状态,ApexCharts无法正确计算容器尺寸,需要在模态框完全显示后触发图表重绘。
1. 监听模态框显示完成事件
Bootstrap模态框在完全显示后会触发shown.bs.modal事件,我们需要在这个时机强制重绘图表。
2. 绑定图表实例并执行重绘
通过@ViewChild获取ApexCharts组件实例,调用其内部的render()方法完成重绘。
3. 确保图表容器有明确尺寸
给图表容器添加固定宽高样式,避免ApexCharts无法识别容器边界。
修改后的代码
HTML部分
<div #croSellWiseModal="bs-modal" aria-hidden="true" bsModal class="modal fade" id="croSellWiseModal" tabindex="-1" (shown.bs.modal)="onModalShown()"> <div class="modal-dialog modal-xl modal-dialog-centered"> <div class="modal-content border-0 p-0"> <div class="modal-body p-0"> <div style="height: auto;"> <div class="row"> <div class="col-md-3"> <div class="card h-100 border-0 shadow-none" style="background:#FFF2F6;"> <div class="card-body"> <div class="d-flex justify-content-center"> <p class="lg-q-link">Cross-Selling</p> </div> <div class="d-flex justify-content-center"> <p class="lg-q-link">Overall Score</p> </div> <div class="d-flex justify-content-center"> <ng-container> <!-- 给容器添加固定尺寸 --> <div class="apex-charts-ds" style="width: 200px; height: 210px;"> <!-- 添加#chartSell标记用于获取实例 --> <apx-chart #chartSell [series]="chartOptionsSell.series" [chart]="chartOptionsSell.chart" [plotOptions]="chartOptionsSell.plotOptions" [responsive]="chartOptionsSell.responsive" [colors]="['#F83E77']" ></apx-chart> </div> </ng-container> </div> <!-- 其余原有内容保持不变 --> </div> </div> </div> <!-- 其余列内容保持不变 --> </div> </div> </div> </div> </div> </div>
TypeScript部分
import { Component, ViewChild } from '@angular/core'; import { ChartComponent } from 'ng-apexcharts'; import { ChartOptions } from 'apexcharts'; @Component({ // 组件元数据保持不变 }) export class YourComponent { @ViewChild('chartSell') chartSell!: ChartComponent; public chartOptionsSell: ChartOptions; constructor() { this.chartOptionsSell = { series: [60], chart: { type: 'radialBar', height: 210, }, plotOptions: { radialBar: { hollow: { size: '50%', }, track: { background: '#FBD3DF', }, dataLabels: { show: true, name: { show: false, }, value: { color: '#0B5ED7', fontWeight: 600, fontSize: '20px', show: true, formatter: (val: any) => { return `${val}%`; }, offsetY: 5, }, total: { show: false, }, }, }, }, responsive: [ // 修复过小的断点值,改为合理的移动端断点 { breakpoint: 768, options: { chart: { height: 120, }, }, }, ], }; } // 模态框显示完成后触发图表重绘 onModalShown(): void { // 加短延时确保容器布局稳定 setTimeout(() => { if (this.chartSell?.chartRef) { this.chartSell.chartRef.render(); } }, 100); } }
关键修改说明
- 绑定模态框事件:通过
(shown.bs.modal)监听模态框完全显示的时机,避免提前执行重绘。 - 固定容器尺寸:给图表容器添加明确的宽高,解决ApexCharts无法识别隐藏容器尺寸的问题。
- 修复响应式断点:将原断点值
210改为768,符合移动端适配逻辑。 - 延时重绘:添加100ms延时确保模态框布局完成,避免重绘时机过早导致无效。
内容的提问来源于stack exchange,提问作者core114
相关产品推荐
相关产品推荐

