When working with multiple charts on Angular ChartJs, the data may not display properly

My goal is to display multiple Charts in a single page using Angular. I came across an Example that uses ViewChildren:

const baseConfig: Chart.ChartConfiguration = {
  type: 'pie',
  options: {
    responsive: true,
  }
};

@ViewChildren('chart', { read: ElementRef }) chartElementRefs: QueryList<ElementRef>;
  chartData: Chart.ChartData[] = [
    {
      labels: ['1500', '1600', '1700', '1750', '1800', '1850', '1900', '1950', '1999', '2050'],
      datasets: [{
        data: [86, 378, 106, 306, 507, 111, 133, 221, 783, 5000],
        borderColor: 'red',
        fill: false
      }]
    },
    {
      labels: ['1500', '1600', '1700', '1750', '1800', '1850', '1900', '1950', '1999', '2050'],
      datasets: [{
        data: [86, 378, 106, 306, 507, 111, 133, 221, 783, 5000].reverse(),
        borderColor: 'blue',
        fill: false
      }]
    }
  ];

  ngAfterViewInit() {
    this.charts = this.chartElementRefs.map((chartElementRef, index) => {
      const config = Object.assign({}, baseConfig, { data: this.chartData[index] 
    });
    console.log(chartElementRef);
    return new Chart(chartElementRef.nativeElement, config);
  });
}

I attempted to achieve the same functionality within a method:

@ViewChildren('chart', { read: ElementRef }) chartElementRefs: QueryList<ElementRef>;
chartData: Chart.ChartData[] = []

createChartData(){
  var arrayChart: any = []
  console.log('number of charts', this.numberOfCharts);

  for (var i = 0; i < this.numberOfCharts; i++){
    var pie = {
      labels: ["Disks", "Mgmt", "Hardware", "FC", "Vols&Pols"],
      datasets: [{
        data: [20, 20, 20, 20, 20],
        backgroundColor: ["#008000", "#008000", "#008000", "#008000", "#008000"]
      }]
    }
    arrayChart.push(pie);
  }
  this.chartData= arrayChart;
  this.charts = this.chartElementRefs.map((chartElementRef, index) => {
    const config = Object.assign({}, baseConfig, { data: this.chartData[index] 
  });
  console.log(chartElementRef);
  return new Chart(chartElementRef.nativeElement, config);
  });
}

HTML:

<div *ngFor="let chart of chartData">
    <canvas #chart></canvas>
</div>

Even after calling the method in ngAfterViewInit(), the Charts are not being displayed. When following the example structure, it works perfectly and displays two Pie Charts. Any insights on why this could be happening?

EDIT

The objective is to implement this functionality within a method to subscribe from a Service.

Answer №1

Give this one a shot

CSS

<style>
  .chart-container {
    display: flex;
    justify-content: center;
  }
  canvas {
    height: 400px;
    width: 400px;
  }
</style>

JavaScript

const chartData = [
  {
    labels: ['January', 'February', 'March', 'April'],
    datasets: [{
      data: [10, 20, 15, 30],
      borderColor: 'green',
      fill: false
    }]
  },
  {
    labels: ['A', 'B', 'C', 'D'],
    datasets: [{
      data: [50, 70, 60, 80].reverse(),
      borderColor: 'purple',
      fill: false
    }]
  }
];

let charts = [];

document.addEventListener('DOMContentLoaded', function() {
  const chartContainers = document.querySelectorAll('.chart-container');

  chartContainers.forEach((container, index) => {
    const ctx = container.querySelector('canvas').getContext('2d');
    const config = {
      type: 'line',
      data: chartData[index]
    };
    
    charts.push(new Chart(ctx, config));
  });
});

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

Enhance your React application by making two API requests in

Below is the React Component that I am working on: export default function Header () { const { isSessionActive, isMenuOpen, isProfileMenuOpen, setIsMenuOpen, closeMenu, URL } = useContext(AppContext) const [profileData, setProfileData] = useState({}) ...

Prevent discrepancies between the outcome on the server and the client side

My website utilizes a combination of PHP and JavaScript for processing results - some server-side, some client-side. Solely relying on JavaScript can cause issues with search engine crawling, while using only PHP may not provide real-time responses accura ...

In order to resolve this issue, I must eliminate any duplicate objects and then calculate the total sum using JavaScript

I have successfully removed the duplicates so far, but now I am stuck on how to sum the Total_Quantity. Is there a way to achieve this within the reduced method itself? Any help would be appreciated. Thank you. const test = [ { Item_Nam ...

What is the most efficient way to restrict multiple input fields, each using v-model, to only accept numeric values in Vue.js without duplicating code for every input field?

I have several input fields in Vue.js that I want to restrict to only accept numbers. I want to prevent users from entering any characters except digits from 0-9. I managed to achieve this successfully with a solution that is resistant to copy-paste: C ...

Modifying shapes and figures in three-dimensional Javascript

I am currently struggling to transform a cube into a sphere in Three.js either after a specific time interval or upon an event click. I have attempted changing the geometry property from BoxGeometry to SphereGeometry with no success. Despite trying some po ...

What could be causing this program to continuously add values to the message table whenever the page is refreshed?

Looking for a simple chatting system using php, mysql, html, css and javascript? Check out this code snippet. However, there seems to be an issue with the message sending functionality. Every time a user sends a message and refreshes the page, the same m ...

Using TypeScript to filter and compare two arrays based on a specific condition

Can someone help me with filtering certain attributes using another array? If a condition is met, I would like to return other attributes. Here's an example: Array1 = [{offenceCode: 'JLN14', offenceDesc:'Speeding'}] Array2 = [{id ...

How can Angular HttpClient be used to convert from Http: JSON.parse(JSON.stringify(data))._body?

When using the Http module, you can use this method: Http service: let apiUrl = this.apiUrl + 'login'; let headers = new Headers({'Content-Type': 'application/json'}); return this.http.post(apiUrl, JSON.stringify(model), {h ...

ESLint is indicating an error when attempting to import the screen from @testing-library/react

After importing the screen function from @testing-library/react, I encountered an ESLint error: ESLint: screen not found in '@testing-library/react'(import/named) // render is imported properly import { render, screen } from '@testing-lib ...

Exploring the potential of AssemblyScript in creating immersive WebXR

I have been exploring three.js and webXR for some time now, and I wanted to incorporate it into assembly script. While I know how to make webXR work in TypeScript, I encounter an error when trying to use it in assembly script with the import statement. Her ...

How about "Temporary and localized responses with Discord.JS?"

Recently, I've been diving into the world of localization on my Discord Bot and had a thought. Localization allows you to tailor replies in different languages based on the user's language settings. For example, take a look at this code snippet ...

Preventing document.getElementById from throwing errors when the element is null

Is there a way to handle null values returned by document.getElementById in JavaScript without adding if statements or checks to the code? I'm looking for a solution that allows the execution of subsequent JavaScript calls even after encountering a nu ...

steps to adjust screen zoom back to default after automatic zoom in forms

I'm not very well-versed in javascript/jquery and have been on an extensive search for a solution to my specific problem. While I've come across some close answers, I am struggling to adapt them to fit my own scenario. On my website, I have a fo ...

Decipher the JSON data for a Facebook cover photo

I am utilizing the Facebook Graph API to retrieve the user's cover picture. By accessing the link provided at , a JSON object containing the picture link is returned. How can I fetch this link using JQuery or JavaScript? Here is my attempt: HTML: & ...

How can I attach an existing event to a dynamically loaded element using AJAX?

In the main page of my website, there is a button: <button class="test">test</button> Additionally, I have included the following script in my code: $('.test').on('click',function(){ alert("YOU CLICKED ME"); } ...

Using Ajax without implementing JavaScript

Is it possible to develop an application that utilizes Ajax without relying on JavaScript, allowing it to function even if JavaScript is disabled by the user in their browser? Are there any restrictions or limitations to consider? ...

Is it possible for me to identify the original state of a checkbox when the page first loaded, or the value it was reset to when `reset()` was

When a webpage is loaded, various input elements can be initialized as they are declared in the HTML. If the user modifies some of the input values and then resets the form using reset(), the form goes back to its initially loaded state. I'm curious, ...

Steps to generate an accurate file order using Typescript:

Consider the scenario with two typescript files: In File a.ts: module SomeModule { export class AClass { } } And in File b.ts: module SomeModule { export var aValue = new AClass(); } When compiling them using tsc -out out.js b.ts a.ts, there are ...

Converting an ajax request to CORS

Would appreciate some guidance on accessing an API through my localhost using the code below: $.ajax({ url: "http://domain.xxx.net/api/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d7a3b8bcb2b9a4f9bda4b8b9e8b2ba ...

Encountering a Content Security Policy error upon deploying a jhipster Angular application on Heroku and attempting to access Marketo REST APIs

I developed a monolith application using jhipster, based on Angular. I leveraged Angular to make http calls to the Marketo REST APIs and everything was running smoothly in my local environment. I was able to successfully generate an access token, retriev ...