Problems in rendering Gantt Chart in angular 15 using d3

62 Views Asked by At

Trying to implement gantt chart using d3 in angular 15, the problem with the rendering. The data flow is correct, SVG and rectangles are created with my dummy data.

private data = [
    { task: 'Task 1', startTime: '2013-01-01', endTime: '2013-01-10' },
    { task: 'Task 2', startTime: '2013-01-05', endTime: '2013-01-15' },
  ];

private drawChart(): void {
    const margin = { top: 20, right: 30, bottom: 30, left: 40 };
    const width = 800 - margin.left - margin.right;
    const height = 400 - margin.top - margin.bottom;
    console.log('margin', margin);
    const svg = d3
      .select('#gantt-container')
      .append('svg')
      .attr('width', width + margin.left + margin.right)
      .attr('height', height + margin.top + margin.bottom)
      .append('g')
      .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');

    console.log('SVG created:', svg);

    svg
      .selectAll('rect')
      .data(this.data)
      .enter()
      .append('rect')
      .attr('x', (d) => this.calculateXPosition(new Date(d.startTime), width))
      .attr('y', (d, i) => i * 30)
      .attr('width', (d) =>
        this.calculateWidth(new Date(d.startTime), new Date(d.endTime), width)
      )
      .attr('height', 20)
      .style('fill', 'steelblue');

    console.log('Rectangles created:', svg.selectAll('rect').nodes());
  }

  private calculateXPosition(date: Date, width: number): number {
    return (date.getTime() / this.getMaxMilliseconds()) * width;
  }

  private calculateWidth(
    startDate: Date,
    endDate: Date,
    width: number
  ): number {
    return (
      ((endDate.getTime() - startDate.getTime()) / this.getMaxMilliseconds()) *
      width
    );
  }

  private getMaxMilliseconds(): number {
    const maxDate = d3.max(this.data, (d) => new Date(d.endTime) as Date);
    return maxDate ? maxDate.getTime() : 0;
  }

scaleTime().doamin() also not accepting the parameters that's why calculating scale and width manually.

Nothing is displayed on the page Here's my template:

<div id="gantt-container"></div>

and CSS:

#gantt-container { width: 100%; height: 400px; }

Also tried the @viewChild but still no success. Please help!

0

There are 0 best solutions below