Third party JS in Angular2 typescript

2020-03-01 09:08发布

问题:

I'm new to angular and typescript, so this is probably really basic.

I'm trying to make an angular2 component with a chart (using Chart.js) in the template.

I realize there is a chart directive being developed, that specifically uses Chart.JS, but I would like to understand how to do this, as it will undoubtedly come up in an instance where a directive isn't available.

So far I've tried to do this simple thing in the template:

<canvas id="chart"></canvas>
<script> 
$(function () {
//instantiate chart on $("#chart")
});
</script>

But this javascript doesn't even run when the template has been loaded by angular2.

How would I go about this?

回答1:

Okay - with the help of @Pogrindis I think I found a usable, not too complex solution.

By simply adding the typing definition for chart.js from here and referencing it in a custom directive I finally have this:

chart.directive.ts

/// <reference path="../../typings/chartjs/chart.d.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 { }

and template.html:

<canvas id="myChart" chart width="400" height="400"></canvas>