Chartjs-How to display Firestore data on Chart.js in Angular?

1👍

import { Component, OnInit } from '@angular/core';
import { Chart } from 'chart.js';
import { AngularFirestore } from '@angular/fire/firestore';

@Component({
  selector: 'app-chart',
  templateUrl: './chart.component.html',
  styleUrls: ['./chart.component.css'],
})
export class ChartComponent implements OnInit {
  chart: Chart;
  data: any[] = []; // Your Firestore data will be stored here

  constructor(private firestore: AngularFirestore) {}

  ngOnInit() {
    this.firestore
      .collection('yourFirestoreCollection') // Replace with your Firestore collection name
      .valueChanges()
      .subscribe((data) => {
        this.data = data; // Store Firestore data in the 'data' array
        this.createChart();
      });
  }

  createChart() {
    // Format your Firestore data for Chart.js
    const labels = this.data.map((item) => item.dateField); // Replace 'dateField' with your Firestore date field name
    const values = this.data.map((item) => item.valueField); // Replace 'valueField' with your Firestore value field name

    this.chart = new Chart('MyChart', {
      type: 'line',
      data: {
        labels: labels,
        datasets: [
          {
            label: 'Weight',
            data: values,
            backgroundColor: 'blue',
          },
        ],
      },
      options: {
        aspectRatio: 2.5,
      },
    });
  }
}

Leave a comment