Implementing the displayChart method

Last but not least, we can now implement the method that will render the chart. The displayChart function accepts a ChartDetails object, containing everything we need to know in order to render.

Before we implement this method, we first need to import Chart.js and retrieve the canvas element from the DOM:

  1.  Add the following import at the top of the world-explorer-view.ts file: import Chart = require("chart.js");. That is all we need to do in order to load Chart.js!
  2.  Add a private and read-only class field for the canvas: private readonly _canvas: HTMLCanvasElement;. It can be marked as readonly because we won't need to reassign it later.

Now, add the following code to the constructor:

this._canvas = document.getElementById("worldExplorerChart") as HTMLCanvasElement; 
if (!this._canvas) { 
    throw new Error("Could not initialize the view. The 
'worldExplorerChart' element id was not found. Was the
template changed?"); }

Then, we'll declare an additional private class field for the chart; we'll use that single reference to render our chart: Add the following declaration at the class level: private _chart?: Chart;.

Now, implement the displayChart method as follows.

First of all, as usual, add a defensive check:

if (!chartDetails) { 
    throw new Error("The chart details must be provided!"); 
} 

Next, we need to create two arrays:

  1. One with the labels of our data: In our case, the date property of each DataPoint instance
  2. One with the values: In our case, the value property of each DataPoint instance

Here's the code:

const dataLabels: string[] = []; 
const dataValues: number[] = []; 

chartDetails.data.forEach(dataPoint => { 
    dataLabels.push(dataPoint.date); 
    dataValues.push(dataPoint.value); 
}); 

Now, we need to make sure that, whenever we try to render a new chart, the previous one (if there was one) gets removed:

if(this._chart) { 
    this._chart.clear(); 
    this._chart.destroy(); 
} 

Finally, here's the code that generates the chart:

this._chart = new Chart(this._canvas, { // <1> 
    type: chartDetails.chartType, // <2> 
    data: { // <3> 
        labels: dataLabels, // <4> 
        datasets: [ // <5> 
            { 
                data: dataValues // <6> 
                label: chartDetails.dataLabel, // <7> 

                // <8> 
                fill: false, 
                lineTension: 0.1, 
                backgroundColor: "rgba(75,192,192,0.4)", 
                borderColor: "rgba(75,192,192,1)", 
                borderCapStyle: "butt", 
                borderDash: [], 
                borderDashOffset: 0.0, 
                borderJoinStyle: "miter", 
                pointBorderColor: "rgba(75,192,192,1)", 
                pointBorderWidth: 1, 
                pointHoverRadius: 5, 
                pointHoverBackgroundColor: "rgba(75,192,192,1)", 
                pointHoverBorderColor: "rgba(220,220,220,1)", 
                pointHoverBorderWidth: 2, 
                pointRadius: 1, 
                pointHitRadius: 10, 
            } 
        ] 
    }, 
    options: { // <9> 
        animation: { // <10> 
            animateRotate: true, 
            easing: "easeOutQuart" 
        }, 
        responsive: true, // <11> 
        scales: { 
            xAxes: [{ // <12> 
                display: true, 
                scaleLabel: { 
                    display: true, 
                    labelString: chartDetails.yAxisLabel 
                } 
            }],
            yAxes: [{ // <13> 
                display: true, 
                scaleLabel: { 
                    display: true, 
                    labelString: chartDetails.yAxisLabel 
                } 
            }] 
        }, 
        title: { // <14> 
            display: true, 
            text: chartDetails.title 
        } 
    } 
}); 

As you can see, creating a chart using Chart.js is really simple. The difficulty arises simply because of the various possibilities of the library.

Here are more details about the preceding code:

  1. To create the chart, we create a new instance of the Chart class provided by Chart.js:
    1. The first thing that we pass to its constructor is the canvas element.
    2. The second thing is the configuration object, which contains the data, the labels, the options, and so on.
  2. The type property is used to define the type of chart to render. The list of supported types can be found here: https://www.chartjs.org/docs/latest/charts.
  3. The data property is used to provide the data of the chart.
  4. The data is composed of labels, representing the label associated with each data point and datasets, accepting an array of data sets.
  5. The actual data is passed through the data property.
  6. Each dataset, of course, contains values and has a specific label.
  7. It is also possible to define many settings for each dataset, including colors, borders, background, points, and many others.
  8. Through the options object, we can further configure the chart to generate.
  9. With the animation options, we can control the animation when the data is rendered.
  10. When the responsive option is enabled, it adapts the size of the canvas depending on the available screen real estate.
  1. With the scales option, we can configure the different axes, their labels, and so on.
  2. Finally, with the title options, we can define and configure the title of the chart.

That's it for the chart generation. Make sure to check the awesome documentation of Chart.js, as there is a whole lot more to discover: https://www.chartjs.org/docs/latest.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.115.195