Guide on displaying information on a pie chart in Angular 2 using ng2-charts

How can I display data on a pie chart like this?

Like shown in the image below:

<canvas baseChart  class="pie"
  [data]="Data"
  [labels]="Labels"
  [colors]="Colors"
  [chartType]="pieChartType">
</canvas>

 public Labels:string[]=['Female','Male'];
 public Data:any =[51,30];
 public pieChartType:string = 'pie';
 public Colors:any = 
 [
{
  backgroundColor: [      
  'green',
  'red'
  ]
  }
]; 

Answer №1

To begin, execute the following npm commands:

npm install ng2-charts --save

npm install chart.js --save

Remember: It is crucial to embed Chart.js in your application by including it in your index.html file.

<script src="node_modules/chart.js/src/chart.js"></script>

Next, import ChartsModule in App.module.ts

import { ChartsModule } from 'ng2-charts';
imports: [ChartsModule]

For your Component.html file:

<div style="display: block">
  <canvas baseChart
          [data]="pieChartData"
          [labels]="pieChartLabels"
          [chartType]="pieChartType"
          (chartHover)="chartHovered($event)"
          (chartClick)="chartClicked($event)"></canvas>

In your Component.ts file:

public pieChartLabels: string[] = ['Male', 'Female'];
  public pieChartData: number[] = [51, 30];
  public pieChartType: any = 'pie';

  // events
  public chartClicked(e: any): void {
    console.log(e);
  }

  public chartHovered(e: any): void {
    console.log(e);
  }

This code functions as expected and should work smoothly for you.

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

Creating a class and initializing it, then implementing it in other classes within an Angular application

Trying to grasp some angular fundamentals by creating a class structure. Unsure if this is the right approach. export class Cars{ Items:Car[]=[]; constructor() { this.Items = [ { id: "1", name: "Honda" ...

The AppModule's CanLoad protector

I recently developed an Angular application using angular-cli and successfully implemented CanLoad guard for my modules. The CanLoad check verifies if the user is logged in before loading a module. My question is, can I apply CanLoad guard to AppModule as ...

Transform a standard array of strings into a union string literal in TypeScript

I'm currently developing a module where users can specify a list of "allowable types" to be utilized in other functions. However, I'm encountering challenges implementing this feature effectively with TypeScript: function initializeModule<T ex ...

Trigger a function upon a user's departure from a page or route in Angular 2

Is there a way to trigger a function only when the current route changes away from a specific component, such as when navigating away from "..../user/user-details"? I want this method to execute regardless of whether the route is changed through user inter ...

Switch up a button counter

Is there a way to make the like count increment and decrement with the same button click? Currently, the code I have only increments the like count. How can I modify it to also allow for decrements after increments? <button (click)="toggleLike()"> ...

Issue encountered during rendering: "TypeError: Attempting to access property '_t' of an undefined object" while running a Unit Test using Jest

I spent hours troubleshooting a unit test for my Vue.js component, but no matter how much I searched the internet, I kept encountering this error: console.error node_modules/vue/dist/vue.runtime.common.dev.js:1884 TypeError: Cannot read property ' ...

Angular 4's Mddialog experiencing intermittent display problem

While using MDDialog in my Angular app, I've encountered a couple of issues. Whenever a user clicks on the div, flickering occurs. Additionally, if the user then clicks on one of the buttons, the afterclose event is not triggered. Can anyone provide ...

Having trouble integrating Azure with my Ionic2/Angular2/Cordova app

I am currently developing with the Ionic2 Blank app template. I encountered an issue when trying to set up Azure using the following line of code in home.ts: import azureMobileClient from 'azure-mobile-apps-client'; . The deployment process wen ...

An issue has occurred: Cannot access the properties of an undefined object (specifically 'controls')

I encountered an error message stating "TypeError: Cannot read property 'controls' of undefined" in the code that I am not familiar with. My goal is to identify the source of this error. Below is the HTML code snippet from my webpage: <div ...

What causes Gun.js to generate duplicate messages within a ReactJs environment?

I need assistance with my React application where gun.js is implemented. The issue I am facing is that messages are being duplicated on every render and update. Can someone please review my code and help me figure out what's wrong? Here is the code s ...

Instructions for authenticating with Google silently in the background

I implemented a Google authentication system based on the tutorial provided in this blog post. Link to Tutorial However, I am facing an issue where a popup always appears for users to login. I would prefer the login process to occur in the background, wh ...

The Order ID field in the Serenity-Platform's Order Details tab is not registering orders

I've been working on replicating the functionality of Orders-Order detail in my own project. https://i.stack.imgur.com/Bt47B.png My custom module is called Contract and Contract Line item, which I'm using to achieve this. https://i.stack.imgur ...

The properties in Typescript, specifically 'value', are not compatible with each other

I've encountered an error while working on a TypeScript project with React Context. The error message states: Argument of type 'Context<{}>' is not assignable to parameter of type 'Context<IsProductContext>'. The type ...

Unable to retrieve rxjs resource

After upgrading to rxjs 5.4.3, I encountered an error in the browser. Despite having "rxjs": "5.4.3" installed in my package.json, I cannot seem to resolve this error message. Here's the content of my ts file: import { Injectable ...

Ways to retrieve the quantity of a particular value within an object using TypeScript

I'm inquiring about how to retrieve the number of a specific value within an object using TypeScript. Here is the structure of the object: obj : TestObject = { name: "test", street: "test" subobj1: { status: warning, time: ...

Guide to modifying the root directory when deploying a Typescript cloud function from a monorepo using cloud build

Within my monorepo, I have a folder containing Typescript cloud functions that I want to deploy using GCP cloud build. Unfortunately, it appears that cloud build is unable to locate the package.json file within this specific folder. It seems to be expectin ...

A guide on displaying an Angular Component within a Thymeleaf page

Currently, I am faced with the task of integrating Angular and Thymeleaf. This is necessary because I have developed a dynamic graph using Angular and now need to incorporate it into an existing project that utilizes Thymeleaf. Are there any simplified m ...

The Ngrx selector fails to activate when the reducer modifies the portion

In my Angular 2 application, I heavily utilize Ngrx stores which have proven to be extremely beneficial. I have a well-structured system in place for my stores where I use selectors to retrieve specific parts of the state. Normally, all the selectors work ...

The Angular component fails to retrieve data from a subscribed service when the data is being fetched from the sessionStorage

Within my Angular application, there exists a service that handles incoming objects by adding them to a list of objects, then saving the updated array to sessionStorage. This service also sends the updated list to another application that is subscribed to ...

Leveraging Angular Observables for seamless data sharing across components

As I embark on developing my very first Angular app, I have encountered a challenge with filtering a list of book objects based on their gender attribute. The issue lies in sharing data between components – specifically the filteredData variable and the ...