Chartjs-plugin-datalabels: Using the plugin with Angular 5

Created on 25 Apr 2018  路  3Comments  路  Source: chartjs/chartjs-plugin-datalabels

Hi,
I'm trying to create a simple doughnut chart using Chart.js and datalabels in Angular 5.
I followed the docs but could not get it to work.
Specs:
Angular v5
Chart,js v2.7.2
chartjs-plugin-datalabels v0.3.0

Here is my code:

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { Chart } from 'chart.js';

@Component({
  selector: 'app-root',
  template: `
  <div style="height: 300px; width: 300px">
    <canvas #myChart>{{doughnut}}</canvas>
  </div>
  `,
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  public doughnut = [];
  @ViewChild('myChart') chart: ElementRef;

  ngOnInit() {
    this.doughnut = new Chart(this.chart.nativeElement, {
      type: 'doughnut',
      data: {
        labels: ['a', 'b', 'c', 'd'],
        datasets: [{
          backgroundColor: '#2c82be',
          data: [12, 34, 23, 65],
          datalabels: {
            anchor: 'end'
          }
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          datalabels: {
            backgroundColor: function (context) {
              return context.dataset.backgroundColor;
            },
            borderColor: 'white',
            borderRadius: 25,
            borderWidth: 2,
            color: 'white',
            font: {
              weight: 'bold'
            },
            formatter: Math.round
          }
        },
        legend: {
          display: true
        },
      }
    });
  }
}

The chart is created but not the labels.
Any help is appreciated.

Edit(SB): code formatting

resolved support

Most helpful comment

Hello @sidv93,

As @simonbrunel noted, you need to import plugin in your component first. Please, add import 'chartjs-plugin-datalabels'; to your import section and it should work as expected.

All 3 comments

Where did you import this plugin (import * from 'chartjs-plugin-datalabels';)? Though, I'm not sure that's the way to go since I'm not familiar with Angular. Maybe @Sadi-1992 (#5) or @bitflower (#12) have some inputs, else that's a question you would better ask on stackoverflow.

Hello @sidv93,

As @simonbrunel noted, you need to import plugin in your component first. Please, add import 'chartjs-plugin-datalabels'; to your import section and it should work as expected.

@deavy and @simonbrunel
Thank you guys. Appreciate the help. It worked

Was this page helpful?
0 / 5 - 0 ratings

Related issues

EmilMoe picture EmilMoe  路  4Comments

boriskogan81 picture boriskogan81  路  4Comments

Laroosta picture Laroosta  路  8Comments

HenriSup picture HenriSup  路  7Comments

ericsvendsen picture ericsvendsen  路  15Comments