我正在Ionic中构建一个应用程序,该应用程序从API获取数据并在水平图表上显示。但是数据的数量不是默认值,因此有时图表高度不够





 

而且我在使水平图自动调整高度方面遇到问题。我已经尝试设置height: auto,但是chart.js设置了默认高度。

我的HTML:

<div class="chart-container" >
    <canvas #barCanvas></canvas>
</div>


我的CSS:

.chart-container{
    position: relative;
    margin: auto;
    height: 110vh;
    width: 80vw;
}


我的JS

private loadChart(){

var backgroundColor = [];

if (this.barChart) {
    this.barChart.destroy();
}
for (let x = 0; x < this.servicos.length; x ++) {
    backgroundColor[x] = this.randomColor();
}


this.barChart = new Chart(this.barCanvas.nativeElement, {
    type: 'horizontalBar',
    data: {
        labels: this.temp.labels,
        datasets: [{
            label:this.consulta.Unidade,
            data: this.temp.valores,
            backgroundColor: backgroundColor,
            borderWidth: 0
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        scales: {
            xAxes:[{
                ticks: {
                    beginAtZero: true
                }
            }],
            yAxes: [{
                ticks: {
                    beginAtZero: true
                }
            }]
        }
    }

});


}

[更新1]我尝试通过在创建表之前比较表的大小来更改height值。它有效,但是我有一个过滤器可以发出新请求并构建新图表,但是height属性设置为chartjs默认值。

if(this.servicos.length <= 10){
    document.getElementById("chart-container").style.height = "300px"
}
if(this.servicos.length > 10 ){
    document.getElementById("chart-container").style.height = "900px"
}

最佳答案

问题出在过滤器上。我使用的是将值发送到另一个新视图this.navCtrl.push(IndicadoresPage, {consulta: consulta});的模式。
我更改为this.viewCtrl.dismiss(consulta)并使用onDidDismiss()捕获了数据。

然后,我比较了数据返回的大小,并根据数据大小设置了chart.canvas.parentNode.style.height = 'XXXpx';

10-04 22:02
查看更多