Issue with formatter function not being returned by Chartjs when using angular doughnut chart for displaying labels and values

Is it possible to display label names and values around the graph near the datasets segment? I have implemented a formatter function, but it is not returning the expected results. If you check my requirement here, you'll see what I'm aiming for. Currently, the graph is displaying as shown in this image, but the labels and values are not being returned as intended.

import { Component, OnInit } from '@angular/core';
import { Chart, ChartOptions, ChartDataset, ChartConfiguration } from 'chart.js';
import 'chartjs-plugin-datalabels';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css']
})

export class YourComponent implements OnInit {
  chart: Chart;
  ngOnInit(): void {
    this.createChart();
  }
  createChart(): void {
    const data: ChartDataset[] = [
      {
        data: [10, 20, 15, 5, 50],
        backgroundColor: [
          'rgb(255, 99, 132)',
          'rgb(255, 159, 64)',
          'rgb(255, 205, 86)',
          'rgb(75, 192, 192)',
          'rgb(54, 162, 235)',
        ],
      },
    ];

    const options: ChartOptions = {
      plugins: {
        datalabels: {
          formatter: function (value, context) {
            const label = context.chart.data.labels[context.dataIndex];
            return label + ': ' + value + '%';
          },
          anchor: 'end',
          align: 'end',
          offset: 10,
          color: 'black',
          font: {
            size: 12,
          },
        },
      },
    };

    const config: ChartConfiguration = {
      type: 'doughnut',
      data: {
        datasets: data,
        labels: ['Red', 'Orange', 'Yellow', 'Green', 'Blue'],
      },
      options: options,
    };

    const canvas = document.getElementById('myChart') as HTMLCanvasElement;

    this.chart = new Chart(canvas, config);

  }
}

Answer №1

According to the chartjs-plugin-datalabels documentation, it is necessary to either globally or locally register the plugin.

To register globally:

import ChartDataLabels from 'chartjs-plugin-datalabels';

Chart.register(ChartDataLabels);

Alternatively, you can register locally:

import ChartDataLabels from 'chartjs-plugin-datalabels';

const config: ChartConfiguration = {
  type: 'doughnut',
  data: {
    datasets: data,
    labels: ['Red', 'Orange', 'Yellow', 'Green', 'Blue'],
  },
  options: options,
  plugins: [ChartDataLabels] // Register locally
};

Check out the StackBlitz demo

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering the "Error: data.map is not a function" issue within Next.js

I'm having trouble understanding why this first fetch call works perfectly: async function getData() { const res = await fetch('https://jsonplaceholder.typicode.com/todos') return res.json() } export default async function Home() { co ...

The data is not being displayed in the table

I am encountering an issue while attempting to populate the table with data received through props by looping over it. Unfortunately, the data is not rendering on the UI :( However, when I manually input data, it does show up. Below is my code: Code for P ...

The deletion of property '1' from the [object Array] is not possible

How to Retrieve a List in My Components Using Input : @Input() usersInput: Section[]; export interface Section { displayName: string; userId: number; title: number; } Here is the Value List : 0: displayName: "بدون نام" ...

Angular form: Choose an option by selecting it and clicking on a button

I need help with my Angular form. I want to allow users to select a value when they click on a button. How can I achieve this? page.html <div *ngFor="let product of products; index as i"> <button (click)="chooseProduct(i)">{{product.name} ...

Attempting to incorporate alert feedback into an Angular application

I am having trouble referencing the value entered in a popup input field for quantity. I have searched through the documentation but haven't found a solution yet. Below is the code snippet from my .ts file: async presentAlert() { const alert = awa ...

What steps are involved in setting up a Typescript-based custom Jest environment?

Currently, I am attempting to develop an extension based on jest-node-environment as a CustomTestEnvironment. However, I encountered an error when trying to execute jest: ● Test suite failed to run ~/git/my-application/tests/environment/custom-test ...

Error encountered: "Unable to locate module 'typescript-Collections' when modifying the module to "umd" or "amd" in the tsconfig.json file."

I recently upgraded to VS17 Enterprise and encountered an issue when trying to import the TypeScript Collections library from GitHub. After following the instructions on their page, I realized that changing the module option in my tsconfig.json file to eit ...

Encountering a discord bot malfunction while on my Ubuntu server

My discord bot runs smoothly on my Windows 10 setup, but when deployed to the server running Ubuntu Server 20, it encounters a specific error. The issue arises when trying to handle incoming chat messages from the server. While I can read and respond to m ...

When working with Angular and NGRX, I often wonder if opening my app in multiple tabs within the same browser will result in all tabs pointing to a single NGRX instance

Is it possible to access my localhost:9000 in multiple tabs? If I open it in 3 tabs, will all those 3 tabs point to a single NGRX instance or will each tab of localhost have its dedicated NGRX instance? I haven't had the chance to test this yet. ...

Typescript displays an error message when attempting to assign a list of string variants to a defined type

Encountering an interesting TS error in the code snippet below: interface Bar { pictureType: "X" | "Y" } interface RT { output: Bar[] } const func = (): RT => { const list = [{ pictureType: 'X', }] r ...

Ways to manipulate the placement of angular material 2 sidenav content to the bottom

I have been experimenting with various methods in CSS to override the existing side nav component in Angular Material 2. mat-sidenav-container { background: white; bottom: 0px !important; /* <---- no success */ } mat-sidenav { width: 300px; ...

update angular component after deleting an item

After deleting a contact in the table, I'm trying to refresh my contact list page but it's not working. Any suggestions? This is the list of contacts in the contact.component.ts file Swal.fire({ title: 'Do you want to delete this contac ...

Angular's ExpressionChangedAfterItHasBeenCheckedError is a common issue that developers encounter

This message continues the discussion about a persistent issue I have been facing. Here is the link to the original thread on Stack Overflow: stackoverflow.com/questions/44596418/angular-throws-expressionchangedafterithasbeencheckederror-with-textarea Af ...

Issues with the functionality of multiselect in Angular2-PrimeNg's reactive forms are currently being experienced

Currently, I am utilizing PrimeNG version 2.0.3 alongside Angular 2.0.0 while implementing reactive forms. My aim is to incorporate the multiselect functionality of PrimeNg into my form. To achieve this, I have taken the following steps: Component.html ...

The activation of Angular 2 pipe

I currently have a variety of models in my collection. When it comes to using pipes in the template, I often run into issues. <div class="card-panel" *ngFor="let card of cards | sortByType"> <card-view [card]="card" [autoupdate]="true">< ...

The TypeScript declaration for `gapi.client.storage` is being overlooked

When I call gapi.client.storage.buckets.list(), TypeScript gives me an error saying "Property 'storage' does not exist on type 'typeof client'." This issue is occurring within a Vue.js application where I am utilizing the GAPI library. ...

Angular Group Formation Issue

I keep encountering the following error: formGroup expects a FormGroup instance. Please pass one in. This is how it looks in HTML: <mat-step [stepControl]="firstFormGroup"> <form [formGroup]="firstFormGroup"> And in my Typ ...

Angular Universal: Missing Title and Meta tags in Page Source

I need help with updating title and meta tags in my Angular Universal Application after a successful api call. app.component.ts import {Component, Inject, OnInit, PLATFORM_ID} from '@angular/core'; import {Meta, Title} from '@angular/platfo ...

Combining two sets of data into one powerful tool: ngx-charts for Angular 2

After successfully creating a component chart using ngx-charts in angular 2 and pulling data from data.ts, I am now looking to reuse the same component to display a second chart with a different data set (data2.ts). Is this even possible? Can someone guide ...

Troubleshooting Angular: Resolving the Fatal Error 'SyntaxError: Unexpected token <' During Startup

I keep encountering this mysterious error repeatedly, especially after making changes to my Angular (2-5) dependencies. SyntaxError: Unexpected token < at eval (<anonymous>) at evaluate (http://localhost:5557/node_modules/systemjs/dist/sy ...