我是角度和打字稿的新手,所以这可能是非常基本的.
我正在尝试使用模板中的图表(使用Chart.js)创建一个angular2组件.
我意识到正在开发一个图表指令,它专门使用Chart.JS,但我想了解如何做到这一点,因为毫无疑问它会出现在指令不可用的情况下.
到目前为止,我试图在模板中做这个简单的事情:
但是当这个模板由angular2加载时,这个javascript甚至都没有运行.
我该怎么做?
好的 - 在@Pogrindis的帮助下,我想我找到了一个可用的,不太复杂的解决方案.
通过简单地从这里添加chart.js的输入定义并在自定义指令中引用它我终于有了这个:
chart.directive.ts
///import {Directive, ElementRef, Renderer, Input} from 'angular2/core'; @Directive({ selector: '[chart]' }) export class ChartDirective { constructor(el: ElementRef, renderer: Renderer) { //el.nativeElement.style.backgroundColor = 'yellow'; var data = { labels: ["January", "February", "March", "April", "May", "June", "July"], datasets: [ { label: "My First dataset", fillColor: "rgba(220,220,220,0.2)", strokeColor: "rgba(220,220,220,1)", pointColor: "rgba(220,220,220,1)", pointStrokeColor: "#fff", pointHighlightFill: "#fff", pointHighlightStroke: "rgba(220,220,220,1)", data: [65, 59, 80, 81, 56, 55, 40] }, { label: "My Second dataset", fillColor: "rgba(151,187,205,0.2)", strokeColor: "rgba(151,187,205,1)", pointColor: "rgba(151,187,205,1)", pointStrokeColor: "#fff", pointHighlightFill: "#fff", pointHighlightStroke: "rgba(151,187,205,1)", data: [28, 48, 40, 19, 86, 27, 90] } ] }; var ctx: any = el.nativeElement.getContext("2d"); var lineChart = new Chart(ctx); ////var lineChartOptions = areaChartOptions; ////lineChartOptions.datasetFill = false; lineChart.Line(data); } }
app.component.ts
import {Component} from 'angular2/core'; import {ChartDirective} from './chart.directive'; @Component({ directives: [ChartDirective], selector: 'chart-graph', templateUrl: '/js/app/template.html' }) export class AppComponent { }
和template.html: