Angular5 - Отзывчивые Highcharts с конфигурацией не работает - PullRequest
0 голосов
/ 03 мая 2018

Я пытаюсь получить отзыв Highcharts с Angular5, используя адаптивную конфигурацию от https://www.highcharts.com/docs/chart-concepts/responsive, например:

responsive: {
  rules: [{
    condition: {
      maxWidth: 500
    },
    chartOptions: {
      legend: {
        enabled: false
      }
    }
  }]
}

Я использую библиотеку angular-highcharts для этого вместе с typescript. Ниже приведен мой код с адаптивной конфигурацией, точно такой, как указано на сайте Highcharts:

import {Component, OnInit} from '@angular/core';
import {Chart} from 'angular-highcharts';
import * as Highcharts from 'highcharts';

@Component({
    selector: 'historical-health-data',
    templateUrl: './historical-health-data.component.html',
    styleUrls: ['./historical-health-data.component.less']
})

export class HistoricalHealthDataComponent {
chart: Chart;

ngOnInit() {
    this.chart = new Chart({                    
                    chart: {
                        type: 'column',
                        height: this.height,
                        style: {fontFamily: 'inherit'}
                    },
                    title: {
                        text: null
                    },
                    exporting: {
                        enabled: false
                    },
                    legend: {
                        enabled: false
                    },
                    credits: {
                        enabled: false
                    },
                    lang: {
                        noData: null
                    },                    
                    plotOptions: {
                        series: {
                            animation: true,
                            connectNulls: true,                            
                            marker: {
                                symbol: 'circle',
                                lineWidth: 1,
                                lineColor: '#fff'
                            }
                        },
                        column: {
                            states: {
                                hover: {
                                    enabled: false
                                }
                            },
                            pointPadding: 0,
                            borderWidth: 0.1,
                            pointWidth: 20,
                            dataLabels: {
                                enabled: false
                            }
                        }
                    },
                    xAxis: {
                        type: 'datetime',
                        tickInterval: 24 * 3600 * 1000,
                        labels: {
                            rotation: -60
                        }
                    },
                    yAxis: {
                        min: 0,                        
                        title: {
                            text: null
                        }
                    },                    
                    series: [{
                        data: [{
                            x: Date.UTC(2012, 0, 1),
                            y: 1
                        }, {
                            x: Date.UTC(2012, 0, 8),
                            y: 3
                        }, {
                            x: Date.UTC(2012, 0, 15),
                            y: 2
                        }, {
                            x: Date.UTC(2012, 0, 22),
                            y: 4
                        }],
                        pointRange: 24 * 3600 * 1000
                    }],
                    responsive: {
                      rules: [{
                        condition: {
                          maxWidth: 500
                        },
                        chartOptions: {
                          legend: {
                            enabled: false
                          }
                        }
                      }]
                    }
                });
            });

     }
}

историко-здоровье-data.component.html:

<div [chart]="chart"></div>

При добавлении адаптивной конфигурации точно так, как указано в документации Highcharts: https://www.highcharts.com/demo/responsive я получаю следующую ошибку:

error TS2345: Argument of type '{ chart: { type: string; height: number; style: { fo
ntFamily: string; }; events: { click: () => v...' is not assignable to parameter of type 'Options'.
  Types of property 'responsive' are incompatible.
    Type '{ rules: { condition: { maxWidth: number; }; chartOptions: { legend: { enabled: boolean; }; }; }[...' is not assignable to type 'ResponsiveOptions[]'.
      Object literal may only specify known properties, and 'rules' does not exist in type 'ResponsiveOptions[]'.

Что я здесь не так делаю? Есть ли лучший способ добиться адаптивных графиков?

Я знаю, что по умолчанию диаграмма должна реагировать, но в моем случае именно так ведет себя ось X, когда браузер свернут до < 700px:

enter image description here

Ось X расширяется и проходит под следующей панелью на странице.

Вот как это должно быть или похоже на:

enter image description here

Ответы [ 2 ]

0 голосов
/ 10 февраля 2019

Я столкнулся с той же проблемой, и это мое решение, и надеюсь, что оно кому-нибудь поможет. Может возникнуть проблема с производительностью большого набора данных.

ngOnInit() {
    this.innerWidth = window.innerWidth;
    this.chartOptions = {
      chart: {
        type: 'line',
        height: 120,
        width: this.innerWidth - 50
      },.....
   };

   this.chart = new Chart(this.chartOptions);
}

Прямая смена экрана и перерисовка.

@HostListener('window:resize', ['$event'])
  onResize(event) {
    this.innerWidth = window.innerWidth;
    this.chartOptions.chart.width = this.innerWidth - 50;
    this.chart = new Chart(this.chartOptions);
  }
0 голосов
/ 05 мая 2018

Использование BreakpointObserver исправило мою проблему, другое небольшое изменение, которое я сделал, это использование chartConfig для создания конфигурации сначала с использованием highcharts Options, а затем привязка данных к объекту Chart. Таким образом, я всегда могу перезагрузить конфигурацию всякий раз, когда мне нужно перерисовать диаграмму. Вот полный код:

    import {Component, OnInit} from '@angular/core';
    import {Chart} from 'angular-highcharts';
    import * as Highcharts from 'highcharts';
    import {Options} from 'highcharts/highstock';
    import {BreakpointObserver} from '@angular/cdk/layout';

    @Component({
        selector: 'historical-health-data',
        templateUrl: './historical-health-data.component.html',
        styleUrls: ['./historical-health-data.component.less']
    })

    export class HistoricalHealthDataComponent {
    chart: Chart;
    chartConfig: Options;

    constructor(private bm: BreakpointObserver) {
        super();
    }

    media() {
            // responsive chart
            this.mediaSubscription = this.bm.observe('(max-width: 1200px)').subscribe(result => {
                //change these values to your desired values as per requirement
                const height = result.matches ? 190 : 300;
                if (!this.height) {
                    // initial display
                    this.height = height;
                    this.load();
                } else if (this.height !== height && this.chart && this.chart.ref) {
                    // redraw
                    this.height = height;
                    this.chartConfig.chart.height = this.height;
                    this.chart = new Chart(this.chartConfig);
                } else {
                    // do nothing
                }
            });
        }

    ngOnInit() {
    this.media();
    this.chartConfig = {
                        chart: {
                            type: 'column',
                            height: this.height,
                            style: {fontFamily: 'inherit'}
                        },
                        title: {
                            text: null
                        },
                        exporting: {
                            enabled: false
                        },
                        legend: {
                            enabled: false
                        },
                        credits: {
                            enabled: false
                        },
                        lang: {
                            noData: null
                        },                    
                        plotOptions: {
                            series: {
                                animation: true,
                                connectNulls: true,                            
                                marker: {
                                    symbol: 'circle',
                                    lineWidth: 1,
                                    lineColor: '#fff'
                                }
                            },
                            column: {
                                states: {
                                    hover: {
                                        enabled: false
                                    }
                                },
                                pointPadding: 0,
                                borderWidth: 0.1,
                                pointWidth: 20,
                                dataLabels: {
                                    enabled: false
                                }
                            }
                        },
                        xAxis: {
                            type: 'datetime',
                            tickInterval: 24 * 3600 * 1000,
                            labels: {
                                rotation: -60
                            }
                        },
                        yAxis: {
                            min: 0,                        
                            title: {
                                text: null
                            }
                        },
                       series: [],
                    };
                //assign/bind the data here after the config is initialized
                    this.chartConfig.series = [{
                            data: [{
                                x: Date.UTC(2012, 0, 1),
                                y: 1
                            }, {
                                x: Date.UTC(2012, 0, 8),
                                y: 3
                            }, {
                                x: Date.UTC(2012, 0, 15),
                                y: 2
                            }, {
                                x: Date.UTC(2012, 0, 22),
                                y: 4
                            }],
                            pointRange: 24 * 3600 * 1000
                        }];
                     //finally create the Chart object here with the config
                        this.chart = new Chart(this.chartConfig);
                });
         }
    }
...