Search code examples
angularhighchartsangular2-highcharts

angular2-highcharts click on point, open user input, display user input in annotation


I am using angular2-highcharts line chart to show visitors per week. I use mock data to create points in the chart. What i would like to achieve is that a user can input something like 'Christmas Eve' when he/she clicks on a point and then an annotation would show at that point.

import { Component, OnInit } from '@angular/core';
import { Data } from '../data';
import { DataService } from '../data.service';
import { ChartOptions, Options } from 'highcharts';

@Component({
  selector: 'app-highcharts',
  templateUrl: './highcharts.component.html',
  styleUrls: ['./highcharts.component.css'],
  template: `
  <div class="container">
  <div class="chart">
  <chart [options]="options">
    <series (click)="click($event)">
    </series>
  </chart>
  <p>{{serieName}} is geselecteerd<p>
  </div>
  `,
})
export class HighchartsComponent implements OnInit {
  title = "Highcharts PoC"
  public options: Options;

  constructor(private dataService: DataService) {

    this.options = {
      title: { text: 'Visitors per week' },
      chart: { zoomType: 'x' }, 
      yAxis: {
        title: {
          text: "Visitors"
        }
      },
      xAxis: {
        title: {
          text: "Week number"
        }
      },
      plotOptions: {
        series: {
          cursor: 'pointer',
          point: {
            events: {
              click: function () {
                {
                    this.serieName = 'Appell';
                    return true
                }
                // alert('Christmas Eve');
                // return true;
              }
            }
          },
          pointStart: 1 // Week number
        }
      },
      series: [{
        name: '2017',
        data: dataService.getHighchartsData()
      }
      ]
    };
  }

  ngOnInit() {
  }
}

Solution

  • I think you are on the right track. I would add a click event to the point

    // component.html
    <chart>
        <series>
            <point (click)="onPointClick($event.context)"></point>
        </series>
    </chart>
    

    Then have a form or something that when submitted adds an annotation to the chart. This is a basic plnkr demonstrating this (http://plnkr.co/edit/UYrRi3cCRyiv1IL4QDt4?p=preview). Here I am using the highcharts annotations module (https://www.npmjs.com/package/highcharts-annotations). You can add an annotation programmatically by doing

    // component.ts
    this.chart.annotations.add({
        title: {
            text: 'Christmas Eve'
        },
        xValue: 24,
        yValue: 12
    });