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?

https://i.sstatic.net/WX9ptm.png

Like shown in the image below:

https://i.sstatic.net/sqlv2m.png

<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

The <router-outlet> in Angular is duplicating the parent component on the page

My issue involves a parent component called RemoteMpnitoringOverviewComponent and a child component called FilterIncidentsComponent, which appears as a modal. However, I am facing the problem of the parent component being displayed twice on the screen. I ...

Vuejs fails to properly transmit data

When I change the image in an image field, the new image data appears correctly before sending it to the back-end. However, after sending the data, the values are empty! Code Commented save_changes() { /* eslint-disable */ if (!this.validateForm) ...

Is there a way to detect changes in a Service variable within an Angular component?

One of my components contains a button that activates the showSummary() function when clicked, which then calls a service named Appraisal-summary.service.ts that includes a method called calc(). showSummary(appraisal) { this.summaryService.calc(appraisal ...

Most effective method for initiating model class attributes

Is there a more efficient way to initialize model classes without explicitly defining each member as undefined? The original concept was to be able to simply use super(data); in extended classes. class Model { construct(data: any) { Object.ke ...

Angular 14 encountered an unexpected issue: There was an unhandled exception with the script file node_modules/tinymce/themes/modern/theme.min.js missing

After attempting to run ng serve, an error message appears: ⠋ Generating browser application bundles (phase: setup) ...An unhandled exception occurred: Script file node_modules/tinymce/themes/modern/theme.min.js does not exist. ⠋ Generating browser ap ...

Display a popup notification when clicking in Angular 2

Can anyone help me with displaying a popup message when I click on the select button that says "you have selected this event"? I am using Angular 2. <button type="button" class="button event-buttons" [disabled]="!owned" style=""(click)="eventSet()"&g ...

After installing Node.js on a Windows machine, the program 'npm' is not identified as an internal or external command, and cannot be executed as an operable program or batch file

I have been searching for a solution to this problem, but none of the suggestions I found seem to work for me. I am currently using a Windows 10 Laptop where I do not have administrative rights. My goal is to run my Angular + NodeJS application on this ma ...

Implementing a custom overwrite function in TypeScript's inheritance

Below is a class that I have: export class RestService { private baseUrl: string; constructor(protected http: HttpClient) { this.baseUrl = environment.LOCAL_URL; } public get<T>(resource: string, params?: HttpParams): Observable< ...

Is there a way for me to receive the status code response from my backend server?

My component makes a call to a servlet, which then sends a POST HTTP request to the backend (using Spring Boot). I want the backend to return the status of the POST request that was sent earlier. This is my code: res= this.CS.postcompetenze(this.comp) Th ...

How can I restrict a generic type to include the new() method?

Is there a way to create a function similar to the following in TypeScript? createEntity<TEntity>(): TEntity { return new TEntity(); } In C#, we can achieve this using: void TEntity CreateEntity<TEntity>() where TEntity : new() How would ...

Tips for effectively managing components during navigation within dynamically loaded components

Our interface includes 3 main navigations for tab views: tab1, tab2, and tab3. Additionally, there is a navigation from the side menu. Each tab dynamically loads components, allowing seamless navigation between different parts of the application. When sw ...

Retrieving fresh data from Firestore with Angular Firebase persistence

My angular 8 app with firestore, built using angularfirebase, is designed to work offline by enabling persistence on firebase. However, I am facing an issue where the local data doesn't update when changes are made in firestore itself or on another de ...

Angular 2: Enhancing communication between directives and host components

I am facing an issue with a component that has 'header', 'content', and 'footer' divs in its template. Within the content div, I have implemented a custom directive to check for overflow in the div element. This part is workin ...

"The act of initializing an EntryComponent in Angular results in the creation of a brand

In my main component, app.component.ts, I have integrated a new service into the providers[] array and initialized it in the constructor: @Component({ selector: 'app-main', templateUrl: './app.component.html', styleUrls: ['. ...

Error: No routes found for 'documents' in Angular 2 RC5

I'm currently in the process of upgrading my application to RC5 and have encountered some challenges. Within my app.routing.ts file, I've included the following: import { Routes, RouterModule } from '@angular/router'; export const ap ...

Develop a query builder in TypeORM where the source table (FROM) is a join table

I am currently working on translating this SQL query into TypeORM using the QueryBuilder: SELECT user_places.user_id, place.mpath FROM public.user_root_places_place user_places INNER JOIN public.place place ON place.id = user_places.place_id The ...

Encountering the error message "TypeError: Unable to access properties of null (reading 'get')" while utilizing useSearchParams within a Storybook file

Looking at the Next.js code in my component, I have the following: import { useSearchParams } from 'next/navigation'; const searchParams = useSearchParams(); const currentPage = parseInt(searchParams.get('page') || '', 10) || ...

A guide on dynamically adding a CSS stylesheet to an Angular component during runtime

I have a requirement to dynamically inject a stylesheet into a component at runtime. The CSS url needs to change depending on user configuration settings and the selected theme. Using styelUrls for static injection won't work in this case, as it is s ...

Having trouble with importing files from a different folder in a React Typescript project

I have a specific folder arrangement set up https://i.sstatic.net/GFOYv.png My goal is to bring both MessageList.tsx and MessageSent.tsx into my Chat.tsx file // Chat.tsx import React from 'react' import {MessageList, MessageSent} from "./ ...

Exploring Angular 4.3 Interceptors: A Practical Guide

I am currently working on a new app that needs authorization headers. Normally, I follow a similar approach to what is described in this article on scotch.io. However, I have recently learned that Angular 4 now fully supports HTTP Interceptors through the ...