我正在一个 Angular2 属性指令内呈现图表(Angular2 团队采用的方法)。这种方法适用于 chart.js,但不适用于 chart.js 2.x
属性指令的代码如下...
import {Directive, ElementRef, Input} from '@angular/core';
declare var Chart:any;
@Directive({
selector: '[bargraph]'
})
export class BarGraphDirective {
el:any;
myChart:any;
constructor(element:ElementRef) {
this.el = element.nativeElement;
}
ngAfterViewInit() {
var canvas = this.el;
var ctx = canvas.getContext('2d');
var _data = {
labels: ["01-01",
"01-04",
"01-15",
"02-03",
"03-25",
"04-03",
"04-14",
"05-27",
"05-27",
"08-03"],
datasets: [{
data: [5, 13, 23, 20, 5, 13, 23, 20, 110, 2],
label: "female",
borderColor: "rgba(197,23,1,0.8)",
backgroundColor: "rgba(197,23,1,0.4)",
hoverBackgroundColor: "rgba(197,23,1,1)",
borderWidth: 1,
pointBorderColor: "rgba(197,23,1,1)",
pointBackgroundColor: "rgba(255,255,255,0.8)",
pointBorderWidth: 1.5,
tension: -1,
yAxisID: "y-axis-1",
}, ],
};
var _options = {
scales: {
xAxes: [{
categorySpacing: 0
}],
yAxes: [{
type: "linear",
display: true,
position: "left",
id: "y-axis-1",
}]
}
};
this.myChart = new Chart(ctx, {
type: "line",
data: _data,
options: _options
});
console.log(ctx);
console.log(this.myChart);
}
}
styling is ...
canvas[bargraph] {
height: 400px !important;
width: 700px !important;
}
这个组件使用了以下的内容...
<canvas bargraph width="700" height="400"></canvas>
在模板中。
一切都如预期的那样。 console.log语句显示ctx和this.myChart都在ngAfterViewInit生命周期钩子内定义。 没有错误。 图表只是不显示。
PS:Chart.js v2代码在Angular2之外可以正常工作,就像这个JS Fiddle一样 - http://jsfiddle.net/beehe4eg/
唯一的区别是DOM的钩子...
document.getElementById("barChart") // for the fiddle
element.nativeElement // in my code as per the approach in the angular 2 docs
文档中的属性指令以及特别针对DOM hook的介绍是...
https://angular.io/docs/ts/latest/guide/attribute-directives.html#!#our-first-draftelement.nativeElement钩子在使用相同方法的情况下,可与chart.js v1与angular2很好地配合使用。
请注意,github repo...https://github.com/valor-software/ng2-charts 正在使用chart.js v1,因此这并没有帮助。
希望有人能解决这个问题或修复它!先感谢了。