如何在ng-bootstrap轮播组件ngb-carousel中用图表div替换img元素
你可以直接在ngbSlide指令包裹的模板内插入任意自定义内容,不需要必须使用官方示例里的图片元素,以下是两种实现方案:
方案1:直接编写两个轮播项(推荐,仅2个图表场景无需额外配置)
<ngb-carousel #carousel [interval]="50000" [wrap]="true"> <!-- 第一个轮播页:栖木乌鸦数量图表 --> <ng-template ngbSlide> <div> <div id = "crowOnPerchChart"> <canvas baseChart [datasets]="crowOnPerchChartData" [labels]="crowOnPerchChartLabels" [options]="crowOnPerchChartOptions" [legend]="crowOnPerchChartLegend" [chartType]="crowOnPerchChartType" > </canvas> </div> </div> </ng-template> <!-- 第二个轮播页:存款金币数量图表 --> <ng-template ngbSlide> <div> <div id = "coinsDepositedChart"> <canvas baseChart [datasets]="coinsDepositedChartData" [labels]="coinsDepositedChartLabels" [options]="coinsDepositedChartOptions" [legend]="coinsDepositedChartLegend" [chartType]="coinsDepositedChartType" > </canvas> </div> </div> </ng-template> </ngb-carousel>
方案2:通过循环生成轮播项(适合图表数量较多的场景)
首先在对应component.ts文件中定义图表配置数组:
// component.ts代码 public chartList = [ { id: 'crowOnPerchChart', data: this.crowOnPerchChartData, labels: this.crowOnPerchChartLabels, options: this.crowOnPerchChartOptions, legend: this.crowOnPerchChartLegend, type: this.crowOnPerchChartType }, { id: 'coinsDepositedChart', data: this.coinsDepositedChartData, labels: this.coinsDepositedChartLabels, options: this.coinsDepositedChartOptions, legend: this.coinsDepositedChartLegend, type: this.coinsDepositedChartType } ]
对应的HTML代码:
<ngb-carousel #carousel [interval]="50000" [wrap]="true"> <ng-template ngbSlide *ngFor="let chart of chartList"> <div> <div [id]="chart.id"> <canvas baseChart [datasets]="chart.data" [labels]="chart.labels" [options]="chart.options" [legend]="chart.legend" [chartType]="chart.type" > </canvas> </div> </div> </ng-template> </ngb-carousel>
可选优化
- 可以给
ngb-carousel添加自定义类调整轮播容器高度,避免不同高度的图表切换时页面跳动:
/* 对应的component.css代码 */ .custom-carousel .carousel-item { height: 400px; /* 按需调整为你的图表固定高度 */ display: flex; align-items: center; justify-content: center; }
- 不需要自动轮播可以将
interval设置为0,仅保留手动滑动切换功能。
内容的提问来源于stack exchange,提问作者Hamza Qureshi
相关产品推荐
相关产品推荐

