``` ts ```ts import {Component, OnInit, AfterViewInit, Input} from '@angular/core'">

Angular D3 line chart

代码:

html

<div class="line-chart">

</div>

ts

import {Component, OnInit, AfterViewInit, Input} from '@angular/core';
import * as d3 from 'd3';

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

  public data = [];

  @Input()
  chartWidth = 400;

  @Input()
  chartHeight = 260;

  @Input()
  xAxisWidth = 20;

  @Input()
  yAxisWidth = 30;

  constructor() { }

  ngOnInit(): void {
    this.data = [
      {year: 2006, popu: 40},
      {year: 2008, popu: 45},
      {year: 2010, popu: 48},
      {year: 2012, popu: 51},
      {year: 2014, popu: 52},
      {year: 2016, popu: 57},
      {year: 2018, popu: 62},
      {year: 2020, popu: 69},
    ];
  }

  ngAfterViewInit() {

    const x = d3.scaleTime()
      .domain(d3.extent(this.data, d => new Date(`${d.year}`)))  // X axis data range
      .range([0, this.chartWidth]);  // X axis width range
    const y = d3.scaleLinear()
      .domain([20, d3.max(this.data, d => d.popu) + 10])  // Y axis data range
      .range([this.chartHeight, 0]); // Y axis height range

    // line area svg group
    const line = d3.select('.line-chart').append('svg')
      .attr('width', this.chartWidth + this.yAxisWidth)
      .attr('height', this.chartHeight + this.xAxisWidth)
      .append('g')
      .attr("transform", `translate(${this.yAxisWidth}, 0)`)

    // draw line svg graph
    const lineDraw = d3.line()
      .x(d => x(new Date(`${d.year}`)))
      .y(d => y(d.popu));

    const svg = d3.select('svg');
    line.append('path').data([this.data])
      .attr('class', 'line')
      .attr('fill', 'none')
      .attr('stroke', 'blue')
      .attr('stroke-width', '2px')
      .attr('d', lineDraw);

    // draw x axis svg graph
    svg.append("g")
      .attr("transform", `translate(${this.yAxisWidth}, ${this.chartHeight})`)
      .call(d3.axisBottom(x));

    // draw y axis svg graph
    svg.append("g")
      .attr("transform", `translate(${this.yAxisWidth}, 0)`)
      .call(d3.axisLeft(y));
  }

}

chart

屏幕快照 2020-06-23 下午12 48 01