import { Component, OnInit, ViewChild, Input, HostListener, ElementRef } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import * as d3 from 'd3';
@Component({
selector: 'app-line-chart',
template: '<div #chart style="width: 100%; height: 100%; margin: 0"></div>',
styleUrls: ['./line-chart.component.scss']
})
export class LineChartComponent implements OnInit {
n;
svg; path; rect; g;
renderedData = [{date: Date.now(), close: 0}];
@ViewChild('chart') chartContainer: ElementRef;
@Input() data: Subject<any>;
@HostListener('window:resize', ['$event'])
onresize(event) {
this.resizeChart()
}
constructor() {
this.n = 100;
const random = d3.randomNormal(0, 100)
const data = d3.range(this.n).map(random)
data.forEach(element => {
this.renderedData.push({date: Date.now(), close: element})
});
}
ngOnInit() {
const el = this.chartContainer.nativeElement;
this.svg = d3.select(el)
.append('svg')
this.rect = this.svg.append('defs').append('clipPath')
.attr('id', 'clip')
.append('rect')
this.path = this.svg.append('g')
.attr('clip-path', 'url(#clip)')
.append('path')
this.resizeChart()
this.data.subscribe(d => this.update(d))
}
resizeChart() {
const el = this.chartContainer.nativeElement;
const w = el.clientWidth;
const h = el.clientHeight;
d3.selectAll('svg')
.style('width', '100%')
.style('height', '100%')
.style('background', '#e5f442')
this.rect.attr('width', w).attr('height', h)
}
update(data) {
const n = 100;
const now = Date.now()
this.renderedData.push({date: now, close: data.payload.x})
const el = this.chartContainer.nativeElement;
const w = el.clientWidth;
const h = el.clientHeight;
const xScale = d3.scaleLinear().domain([0, n - 1]).range([0, w])
const yScale = d3.scaleLinear().domain([-100, 100]).range([h, 0])
const valueline = d3.line()
.x((d, i) => xScale(i))
.y(d => yScale(d.close));
this.path
.data([this.renderedData])
.style('fill', 'none')
.style('stroke-width', 2)
.style('stroke', '#1b3145')
.attr('d', valueline)
.transition()
.duration(500)
.ease(d3.easeLinear)
.attr('transform', null)
.attr('transform', 'translate(' + xScale(-1) + ')')
.transition()
if (this.renderedData.length > n) {
this.renderedData.shift();
}
}
}