import { Component, Input, ElementRef, OnInit, OnChanges, OnDestroy } from '@angular/core';
import { ScriptLoaderService } from '../../library/script-loader.service';
declare const jQuery;
@Component({
selector: 'rd-flot-chart',
template: `
`
})
export class FlotChart implements OnInit, OnChanges, OnDestroy {
@Input("rd-data") data: Array> = []; // [[index,value],[0,34.6653]...]
@Input("rd-height") height: number | string = 300;
constructor(public element: ElementRef, private script: ScriptLoaderService) {
this.script.load(["./assets/js/flot.bundle.js"]);
}
interval;
initialized: boolean;
container: any;
flotElement: any;
previousWidth: number;
ngOnInit() {
this.container = jQuery(this.element.nativeElement).find("#flotChart");
setTimeout(() => { this.render(); }, 10);
}
ngDoCheck() {
if (this.container && this.previousWidth != this.container[0].clientWidth) {
this.previousWidth = this.container[0].clientWidth;
this.render();
}
}
ngOnChanges(changes) {
if (this.initialized) {
if (changes.data) {
this.render();
}
}
}
ngOnDestroy() {
clearInterval(this.interval);
}
render() {
if (this.container[0].clientWidth > 0 && this.container[0].clientHeight > 0) {
this.initialized = true;
this.drawFlot();
}
}
timer() {
if (this.initialized) {
if (this.interval) clearInterval(this.interval);
this.interval = setInterval(() => {
this.flotElement.setData([this.getDynamicData()]);
this.flotElement.draw();
}, 30)
}
}
getDynamicData() {
this.data.push(this.data.shift());
for (let index = 0; index < this.data.length; index++) {
let innerItemArr = this.data[index];
innerItemArr[0] = index; // [index,value] set index
}
return this.data;
}
drawFlot() {
this.flotElement = jQuery.plot(this.container, [this.data], {
series: {
shadowSize: 10
},
lines: {
show: true,
lineWidth: .5,
fill: true,
fillColor: {
colors: [
{
opacity: .1
}, {
opacity: 1
}
]
}
},
yaxis: {
min: 0,
max: 100,
tickColor: "#eee",
tickFormatter: function (t) {
return t + "%"
}
},
xaxis: {
show: false
},
colors: ["#6ef146"],
grid: {
tickColor: "#eee",
borderWidth: 0
}
});
this.timer();
}
}