E. Erfan
E. Erfan

Reputation: 1401

How to add tooltip to line chart written in typescript and angular

I have a line chart in d3js v4 written in typescript. Now I need to add tooltip for each data point. The project is in angular and I am very new to it. In order to add tooltip, I have made a scatterplot on top of the line chart and showed the points. I have handled onmouseover and onmouseout events in component.ts file, but no tooltip is shown. The code is as follows:

import {Component, ElementRef, Input, OnChanges, OnInit, ViewChild} from '@angular/core';
import {RegressionValue} from '../../models/RegressionResult';
import * as d3 from 'd3';


@Component({
  selector: 'app-line-chart',
  templateUrl: './line-chart.component.html',
  styleUrls: ['./line-chart.component.css']
})
export class LineChartComponent implements OnInit, OnChanges {

  @ViewChild('chart') private chartContainer: ElementRef;
  @Input() private data: Array<RegressionValue>;
  private margin: any = {top: 20, right: 20, bottom: 30, left: 50};
  private chart: any;
  private width: number;
  private height: number;
  private xScale: any;
  private yScale: any;
  private lineGenerator: any;

  constructor() { }

  ngOnInit() {
    this.createChart();
    if (this.data) {
      this.updateChart();
    }
  }

  ngOnChanges() {
    if (this.chart) {
      this.updateChart();
    }
  }

  createChart() {
    const element = this.chartContainer.nativeElement;
    this.width = element.offsetWidth - this.margin.left - this.margin.right;
    this.height = element.offsetHeight - this.margin.top - this.margin.bottom;
    const svg = d3.select(element).append('svg')
      .attr('width', element.offsetWidth)
      .attr('height', element.offsetHeight);

    this.chart = svg.append('g')
      .attr('transform', `translate(${this.margin.left}, ${this.margin.top})`);

    this.xScale = d3.scaleTime().rangeRound([0, this.width]);
    this.yScale = d3.scaleLinear().rangeRound([this.height, 0]);

  }

  private makeYGridlines() {
    return d3.axisLeft(this.yScale).ticks(5);
  }

  private makeXGridlines() {
    return d3.axisBottom(this.xScale).ticks(5);
  }

  updateChart() {
    this.lineGenerator = d3.line<RegressionValue>()
      .x(d => this.xScale(d.date))
      .y(d => this.yScale(d.prediction));

    this.xScale.domain(d3.extent(this.data, (d) => d.date));
    this.yScale.domain(d3.extent(this.data, (d) => +d.prediction));

    this.chart.append('g')
      .attr('class', 'grid')
      .attr('transform', 'translate(0,' + this.height + ')')
      .call(this.makeXGridlines().tickSize(-this.height).tickFormat(''));

    this.chart.append('g')
      .attr('class', 'grid')
      .call(this.makeYGridlines().tickSize(-this.width).tickFormat(''));

    const div = this.chart.append('div')
      .attr('class', 'tooltip')
      .style('opacity', 0);

    this.chart.append('path')
      .datum(this.data)
      .attr('fill', 'none')
      .attr('stroke', 'steelblue')
      .attr('stroke-linejoin', 'round')
      .attr('stroke-linecap', 'round')
      .attr('stroke-width', 1.5)
      .attr('d', this.lineGenerator);

    this.chart.selectAll('dot')
      .data(this.data)
      .enter()
      .append('circle')
      .attr('cx', (d) => this.xScale(d.date) )
      .attr('cy', (d) => this.yScale(d.prediction) )
      .attr('r', 2)
      .on('mouseover', (d) => {
                div.transition()
                   .duration(200)
                   .style('opacity', .9);
                div.html('a tooltip <br/>' + d.date +'<br/>' + d.prediction)
                   .style('left', (d3.event.pageX) + 'px')
                   .style('top', (d3.event.pageY - 28) + 'px');
      })
      .on('mouseout', (d) => {
                  div.transition()
                     .duration(500)
                     .style('opacity', 0);
      });


    this.chart.append('g')
      .attr('transform', 'translate(0,' + this.height + ')')
      .call(d3.axisBottom(this.xScale));

    this.chart.append('g')
      .call(d3.axisLeft(this.yScale));

  }
}

The data format is date, prediction.

I had done it before with charts written in d3js by JavaScript, but now that it is typescript, it seems it is not working the same way. I appreciate any help guiding me what I need to do.

Also the result is as follows:

enter image description here

I have checked constantly the console and there is no error there. But the IDE is showing errors for the part I am changing the innerhtml of div element ('a tooltip
' + d.date +'
' + d.prediction).If you need more data pleasekindly let me know. Thank you very much.

Upvotes: 1

Views: 7274

Answers (1)

Safiyya
Safiyya

Reputation: 1393

Two issues : - div cannot be added to the svg element but only to body - use the technique in Angular Styles in component for D3.js do not show in angular 2 to make sure Angular applies your component.css style to you component

Replace

@Component({
  selector: 'app-line-chart',
  templateUrl: './line-chart.component.html',
  styleUrls: ['./line-chart.component.css']
})

const div = this.chart.append('div')
      .attr('class', 'tooltip')
      .style('opacity', 0);

by

@Component({
  selector: 'app-line-chart',
  templateUrl: './line-chart.component.html',
  styleUrls: ['./line-chart.component.css'],
  encapsulation: ViewEncapsulation.Emulated
})
 const div = d3.select("body").append('div')
      .attr('class', 'tooltip')
      .style('opacity', 0);

Upvotes: 2

Related Questions