Home forums Using CanvasJS Angular 4+ with CanvasJS

This topic contains 1 reply, has 2 voices, and was last updated by  Priyanka M S 2 months, 1 week ago.

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #21246

    Ryan
    Member

    Hi,

    How would I create a reusable canvasjs component in Anuglar 4+ projects.
    I’ve tried making one, but not sure how I can pass in ID into the container dynamically.
    I’m getting the error below. The chart seems to be rendered before the child receive the ID from parent.
    Therefore, ID results undefined;

    “CanvasJS Error: Chart Container with id “undefined” was not found”

    [canvasjs.component.ts]

    import { Component, OnInit, Input } from '@angular/core';
    import * as CanvasJS from './CanvasJS';
    
    @Component({
      selector: 'app-canvasjs',
      templateUrl: './canvasjs.component.html',
      styleUrls: ['./canvasjs.component.css']
    })
    export class CanvasjsComponent implements OnInit {
      @Input() chartId: string;
    
      constructor() { }
    
      ngOnInit() {
        console.log(this.chartId);
        let chart = new CanvasJS.Chart(<code>${this.chartId}</code>, {
          theme: 'light2',
          animationEnabled: true,
          exportEnabled: true,
          title: {
            text: 'Monthly Expense'
          },
          data: [{
            type: 'pie',
            showInLegend: true,
            toolTipContent: '<b>{name}</b>: ${y} (#percent%)',
            indexLabel: '{name} - #percent%',
            dataPoints: [
              { y: 450, name: 'Food' },
              { y: 120, name: 'Insurance' },
              { y: 300, name: 'Traveling' },
              { y: 800, name: 'Housing' },
              { y: 150, name: 'Education' },
              { y: 150, name: 'Shopping' },
              { y: 250, name: 'Others' }
            ]
          }]
        });
    
        chart.render();
      }
    
    }

    [canvasjs.component.html]
    <div [id]="chartId" style="height: 370px; width: 100%; margin-left:auto;margin-right:auto;"></div>

    [parent.component.html]

    <mat-card>
       <h2>Chart #1</h2>
       <app-canvasjs [chartId]="canvas1"></app-canvasjs>
      </mat-card>
    #22557

    Priyanka M S
    Member

    Ryan,

    These articles might be of help to you in creating dynamic elements. Please take a look at them
    Creating Dynamic Components in body using Angular
    Dynamic Components in Angular

    __
    Priyanka M S
    Team CanvasJS

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.