Angular-Highchart中的自定义DaterangePicker

时间:2019-06-21 10:12:47

标签: javascript angular highcharts

我在角(v8)中创建了一个类似于this的高图。我想删除默认过滤器,并借助ngx daterangepicker创建一个自定义。我需要过滤数组,但它是complex array。我尝试使用foreach创建多个迭代,但是不起作用。

这是我的TS代码

import { Component, OnInit } from "@angular/core";
import { fadeAnimation } from "../../../../animations.component";
import { StockChart } from "angular-highcharts";
import { HttpClient } from "@angular/common/http";
import * as Highcharts from "highcharts";
import * as moment from "moment";
declare let AdminLTE: any;

@Component({
  selector: "app-metergraph",
  templateUrl: "./graph.component.html",
  styleUrls: ["./graph.component.scss"],
  animations: [fadeAnimation]
})
export class MetersGraphComponent implements OnInit {
  chart: StockChart;
  seriesOptions: any = [];
  ranges: any;
  pickerlang: any;
  seriesCounter = 0;
  names = ["MSFT", "AAPL"];

  constructor(private http: HttpClient) {}

  ngOnInit(): void {
    AdminLTE.init();
    moment.locale("es");
    this.names.forEach((element, i) => {
      this.http
        .get(
          "https://www.highcharts.com/samples/data/" +
            element.toLowerCase() +
            "-c.json"
        )
        .forEach((data: any) => {
          this.seriesOptions[i] = {
            name: element,
            data: data
          };
          this.seriesCounter += 1;
          if (this.seriesCounter === this.names.length) {
            this.createGraph();
          }
        });
    });

    this.ranges = {
      Today: [moment(), moment()],
      Yesterday: [moment().subtract(1, "days"), moment().subtract(1, "days")],
      "Last 7 Days": [moment().subtract(6, "days"), moment()],
      "Last 30 Days": [moment().subtract(29, "days"), moment()],
      "This Month": [moment().startOf("month"), moment().endOf("month")],
      "Last Month": [
        moment()
          .subtract(1, "month")
          .startOf("month"),
        moment()
          .subtract(1, "month")
          .endOf("month")
      ]
    };

    this.pickerlang = {
      format: "DD/MM/YYYY",
      direction: "ltr",
      weekLabel: "W",
      cancelLabel: "Cancelar",
      applyLabel: "Aceptar",
      clearLabel: "",
      daysOfWeek: moment.weekdaysMin(),
      monthNames: moment.monthsShort(),
      firstDay: 1
    };

    Highcharts.setOptions({
      lang: {
        loading: "Cargando...",
        months: [
          "Enero",
          "Febrero",
          "Marzo",
          "Abril",
          "Mayo",
          "Junio",
          "Julio",
          "Agosto",
          "Septiembre",
          "Octubre",
          "Noviembre",
          "Diciembre"
        ],
        weekdays: [
          "Domingo",
          "Lunes",
          "Martes",
          "Miércoles",
          "Jueves",
          "Viernes",
          "Sábado"
        ],
        shortMonths: [
          "Ene",
          "Feb",
          "Mar",
          "Abr",
          "May",
          "Jun",
          "Jul",
          "Ago",
          "Sep",
          "Oct",
          "Nov",
          "Dic"
        ],
        rangeSelectorFrom: "Desde",
        rangeSelectorTo: "Hasta",
        rangeSelectorZoom: "Período",
        downloadPNG: "Descargar imagen PNG",
        downloadJPEG: "Descargar imagen JPEG",
        downloadPDF: "Descargar imagen PDF",
        downloadSVG: "Descargar imagen SVG",
        downloadCSV: "Descargar imagen CSV",
        downloadXLS: "Descargar imagen XLS",
        printChart: "Imprimir",
        resetZoom: "Reiniciar zoom",
        resetZoomTitle: "Reiniciar zoom",
        viewData: "Ver tabla",
        openInCloud: "Ver en web",
        thousandsSep: ",",
        decimalPoint: "."
      }
    });
  }

  createGraph() {
    this.chart = new StockChart({
      xAxis: {
        crosshair: {
          width: 1,
          color: "red"
        }
      },
      rangeSelector: {
        enabled: false
      },
      chart: {
        zoomType: "x",
        panning: true,
        panKey: "shift"
      },

      plotOptions: {
        series: {
          showInNavigator: true
        }
      },
      tooltip: {
        pointFormat:
          '<span style="color:{series.color}">{series.name}</span>: <b>{point.y} litros</b><br/>',
        valueDecimals: 2,
        split: true
      },
      series: this.seriesOptions
    });
  }

  change(data: any) {
    console.log(data["startDate"].toJSON().substring(0, 10));
    console.log(data["endDate"].toJSON().substring(0, 10));
    this.seriesOptions.forEach((element: any) => {
      // console.log(element);
      element["data"].forEach(index => {
        //console.log(index[0]);
        index.forEach((datetime: any) => {
          console.log(datetime); //MULTIPLE ITERATIONS FAIL, MAYBE HIGHCHART HAVE A FUNCTION TO FILTER ARRAY WITH  FIELD VALUES.
        });
      });
      // console.log(element["data"]);
      //console.log(element["data"][0]);
    });
  }
}

这是我的HTML

<div class="content-wrapper">
  <section class="content-header">
    <section class="content">
      <div class="panel panel-default">
        <div class="panel-heading">
          <h5>
            <b>Test</b>
          </h5>
        </div>
        <div class="panel-body">
          <input type="text" ngxDaterangepickerMd [locale]="pickerlang" [(ngModel)]="selected" class="form-control"
            placeholder="Rango de fecha" (ngModelChange)="change($event)" [ranges]="ranges"
            [showCustomRangeLabel]="true" [alwaysShowCalendars]="true" />
          <div [chart]="chart"></div>
        </div>
      </div>
    </section>
  </section>
</div>

最后,我添加了screen页。

所以问题是:如何用timepicker的值过滤这种类型的数组?迭代失败。也许highchart具有发送字段值和过滤器的功能。

1 个答案:

答案 0 :(得分:0)

您可以使用xAxis.setExtremes()方法,该方法允许在渲染时间之后设置轴的最小值和最大值。尝试将其与从日期选择器获取的日期一起使用(日期必须以毫秒为单位):

chart.xAxis[0].setExtremes(1536154200000, 1558099800000);

演示:

API参考:



编辑

可以使用图表事件获取图表实例-所有图表事件功能的上下文都是图表实例。

角度演示(使用highcharts-angular官方包装):

API参考: