3

The error is Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'. HTML Code:

<template> 


    <div class = 'slds-box' >
        <canvas class="line-chart"  width="800" height="450" lwc:dom="manual"></canvas>
    </div>
</template>

JSCode

import { LightningElement,api } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { loadScript, loadStyle } from 'lightning/platformResourceLoader';
import chart from '@salesforce/resourceUrl/chart';


 export default class Chartcmp extends LightningElement {
  @api chartjsInitialized = false;
   @api recordId;
   renderedCallback() {
        if (this.chartjsInitialized) {
          return;
         }
        this.chartjsInitialized = true;
        console.log('chartjs loading');
        Promise.all([
              loadScript(this, chart + '/chart/Chart.min.js')
        ])
    .then(() => {
        this.Initializechartjs();
    })
    .catch(error => {
        this.dispatchEvent(
            new ShowToastEvent({
                title: 'Error loading chartJs',
                message: error.message,
                variant: 'error'
            })
        );
    });
   }

  Initializechartjs() {
    console.log("loaded");
    //Get the context of the canvas element we want to select
    var ctx = this.template.querySelector(".line-chart");
    var lineChart = new Chart(ctx ,{
        type: 'line',
        data: {
            labels: ['Sunday','Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
            datasets: [
                {
                    label:'Day',
                    data: [110, 290, 150, 250, 500, 420, 100],
                    borderColor:'rgba(62, 159, 222, 1)',
                    fill: false,
                    pointBackgroundColor: "#FFFFFF",
                    pointBorderWidth: 4,
                    pointHoverRadius: 5,
                    pointRadius: 3,
                    bezierCurve: true,
                    pointHitRadius: 10
                }
            ]
        },
        options: {  
            legend: {
                position: 'bottom',
                padding: 10,
            },
            responsive: true
        }
       });
      }
}
1
  • I have added Chart.min.js directly to static resource. Commented Nov 28, 2019 at 12:12

2 Answers 2

8

Chart.js uses CSS injection.

The mechanics of how they performed the CSS injection changed between v2.7.3 (the example that has been in the LWC Recipes app until now) and v2.9.3. This led to the CSS injection out and out failing when their algorithm to find a root node to attach the CSS to was returning undefined.

We've just updated the Chart JS example in the LWC Recipes sample app to demonstrate a working example of Chart JS in v 2.9.3. You can see a full implementation there, but here are steps to take to use the current version of chart.js in lwc and preserve the CSS.

First, include both Chart.js and Chart.css in your static resource.

enter image description here

Next, load both the CSS and JS files. Load both the script and the style. Then (according to the Chart.js docs), disable the css injection using Chart.platform.disableCSSInjection. In our case, we'll need to explicitly point to window.Chart.

// import the static resource
import chartjs from '@salesforce/resourceUrl/chartJs';

...
// in the renderedCallback of your class
        Promise.all([
            loadScript(this, chartjs + '/Chart.js'),
            loadStyle(this, chartjs + '/Chart.css')
        ])
            .then(() => {
                // disable CSS injection
                window.Chart.platform.disableCSSInjection = true;

                const canvas = document.createElement('canvas');
                this.template.querySelector('div.chart').appendChild(canvas);
                const ctx = canvas.getContext('2d');
                this.chart = new window.Chart(ctx, this.config);
            })

That should give you a working Chart JS implementation in v2.9.3.

3

I have used this code for Graph and it works fine

<template>
   <div>
       <canvas class="stepped"></canvas>
 </div>
</template>

Js Code-

In static folder "Resources" I have uploaded chartjs static file

import { LightningElement,api,track } from 'lwc';
import { loadScript } from "lightning/platformResourceLoader";
import rexourceContainer from "@salesforce/resourceUrl/Resources"; 

export default class Chartcmp extends LightningElement {
 @api totalcriticalacc;
 @api totalnoncriticalacc;

chartjs = rexourceContainer + "/js/chart.js";
    utilJs = rexourceContainer + "/js/utils.js";
    styleCss = rexourceContainer + "/css/style.css";


    connectedCallback() {
     if (this.chartjsInitialized) {
        return;
      }
      this.chartjsInitialized = true;
      Promise.all([
        loadScript(this, this.utilJs),
        loadScript(this, this.chartjs)

      ])
        .then(() => {  this.generateSteppedChart();
        })
        .catch(error => {
          this.error = error;
        });  
    }
    errorCallback(error) {
      this.error = error;
    }
generateSteppedChart() {
 var barChartData = {
        labels: ["Value1","Value2"],
        datasets: [
          {
            label: "Dataset 1",
            backgroundColor: [
              "#F6AE38",
              "#D93448",
              "grey"
            ],

            data: [ this.value1,this.value2]
          }
        ]
      };
 var dataSet = {
        type: "doughnut",
        data: barChartData,
        options: {
          legend:{display:false},tooltips:{enabled:false},
          cutoutPercentage: 75,
          responsive: true,
          title: {
            display: true,
          }
}};
 const ctx = this.template.querySelector("canvas.stepped").getContext("2d");
      this.steppedChart = new window.Chart(ctx, dataSet);
    }
}

enter image description here

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .