``` ts ```ts import {Component, OnInit, AfterViewInit, Input} from '@a">

Angular D3 Bar chart

代码:

html

<div class="bar-chart">
  <svg></svg>
</div>

ts

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

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

  data = [];

  @Input()
  chartWidth = 300;

  @Input()
  chartHeight = 220;

  @Input()
  xAxisWidth = 20;

  @Input()
  yAxisWidth = 25;

  @Input()
  barWidth = 30;

  constructor() {
    this.data = [
      {name: 'PHP', value: 30},
      {name: 'Python', value: 50},
      {name: 'Go', value: 45},
      {name: 'C', value: 80},
      {name: 'C++', value: 60},
    ];
  }

  ngOnInit(): void {
  }

  ngAfterViewInit() {

    const x = d3.scaleBand()
      .domain(this.data.map(d => d.name))
      .range([0, this.chartWidth]);

    console.log('----!!-----');
    console.log(x('PHP'))
    const bandWidth = x.bandwidth();
    console.log(bandWidth);
    console.log(x.step());

    const y = d3.scaleLinear()
      .domain([0, d3.max(this.data, d => d.value) + 10])  // Y axis data range
      .range([this.chartHeight, 0]); // Y axis height range

    const svg = d3.select('svg');
    const bar = svg.attr('width', this.chartWidth + this.yAxisWidth)
      .attr('height', this.chartHeight + this.xAxisWidth)
      .append('g')
      .attr("transform", `translate(${this.yAxisWidth}, 0)`)

    bar.selectAll('rect')
      .data(this.data)
      .enter()
      .append('rect')
      .attr('class', 'bar')
      .attr('width', this.barWidth)
      .attr('x', (d, i) => bandWidth * (i + 0.5) - this.barWidth / 2)
      .attr('y', d => y(d.value))
      .attr('height', d => (this.chartHeight - y(d.value)))
      .attr('fill', 'steelblue');

    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));
  }
}
屏幕快照 2020-06-23 下午4 02 18