Angular2 has encountered a malfunction with the chart feature

My attempt to create a Bar Chart with this GitHub repository is not working in Chrome. You can view my code on Plunker. Can someone help me identify the issue?

Below is the updated code:

app.ts

import {Component, Pipe, PipeTransform} from 'angular2/core';
import {CORE_DIRECTIVES, NgClass, FORM_DIRECTIVES, Control, ControlGroup, FormBuilder, Validators} from 'angular2/common';
import {CHART_DIRECTIVES} from './ng2-charts.ts'; 

@Component({
    selector: 'my-app',
    templateUrl: 'mytemplate.html',
    directives: [CHART_DIRECTIVES, NgClass, CORE_DIRECTIVES, FORM_DIRECTIVES]
})
export class AppComponent { 
  constructor() {
    console.log('bar demo');
  }

  private barChartOptions = {
    scaleShowVerticalLines: false,
    responsive: true,
    multiTooltipTemplate: '<%if (datasetLabel){%><%=datasetLabel %>: <%}%><%= value %>'
  };
  private barChartLabels = ['2006', '2007', '2008', '2009', '2010', '2011', '2012'];
  private barChartSeries = ['Series A', 'Series B'];
  public barChartType = 'Bar';
  private barChartLegend:boolean = true;

  private barChartData = [
    [65, 59, 80, 81, 56, 55, 40],
    [28, 48, 40, 19, 86, 27, 90]
  ];

  // events
  chartClicked(e:any) {
    console.log(e);
  }
  chartHovered(e:any) {
    console.log(e);
  }
}

app.html

<base-chart class="chart"
           [data]="barChartData"
           [labels]="barChartLabels"
           [options]="barChartOptions"
           [series]="barChartSeries"
           [legend]="barChartLegend"
           [chartType]="barChartType"
           (chartHover)="chartHovered($event)"
           (chartClick)="chartClicked($event)"></base-chart>

If anyone knows of another library that can display data on a bar chart for Angular 2, please suggest it.

Answer №1

Expounding on @Thierry's response with an illustration.

Check out the updated code below:

app.ts

import {Component, DynamicComponentLoader, Injector} from 'angular2/core';
import {CORE_DIRECTIVES, NgClass, FORM_DIRECTIVES, Control, ControlGroup, FormBuilder, Validators} from 'angular2/common';
import {ChartDirective} from './charts.ts';

@Component({
    selector: 'my-app',
    templateUrl: 'mytemplate.html',
    directives: [ChartDirective, NgClass, CORE_DIRECTIVES, FORM_DIRECTIVES]
})
export class AppComponent { 

 constructor() {

    }

}

app.html

<div class="container details-container">
  <topics></topics>
</div>

<div class="graph-container">
    <div class="row no-pad" style="position: relative;">
        <div style="margin-left:14px; z-index: 100; height: 250px;">    
            <canvas id="myChart" chart height="250" width="350"></canvas>
        </div>  
    </div>
</div>

chart.ts

import {Directive, ElementRef, Renderer, Input} from 'angular2/core';
@Directive({
    selector: '[chart]'
})
export class ChartDirective {
    constructor(el: ElementRef, renderer: Renderer) {
        //el.nativeElement.style.backgroundColor = 'yellow';
        var data = {
          labels: ["January", "February", "March", "April", "May", "June", "July"],
          datasets: [
              {
                  label: "My First dataset",
                  fillColor: "rgba(220,220,220,0.5)",
                  strokeColor: "rgba(220,220,220,0.8)",
                  highlightFill: "rgba(220,220,220,0.75)",
                  highlightStroke: "rgba(220,220,220,1)",
                  data: [65, 59, 80, 81, 56, 55, 40]
              },
              {
                  label: "My Second dataset",
                  fillColor: "rgba(151,187,205,0.5)",
                  strokeColor: "rgba(151,187,205,0.8)",
                  highlightFill: "rgba(151,187,205,0.75)",
                  highlightStroke: "rgba(151,187,205,1)",
                  data: [28, 48, 40, 19, 86, 27, 90]
              }
          ]
      };

        var options = {
            scaleBeginAtZero : true,scaleShowGridLines : true,
            scaleGridLineColor : "rgba(0,0,0,.05)",
            scaleGridLineWidth : 1,
            scaleShowHorizontalLines: true,
            scaleShowVerticalLines: true,
            barShowStroke : true,
            barStrokeWidth : 2,
            barValueSpacing : 5,
            barDatasetSpacing : 1,
            legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].fillColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"

          }

        var ctx: any = el.nativeElement.getContext("2d");
        var BarChart = new Chart(ctx);
        BarChart.Bar(data, options);             

    }

}

working plnkr http://plnkr.co/edit/Vfsert1sAJ4dsVR4MdyV?p=preview

Answer №2

Here is a suggestion that may provide some insight:

  • Dealing with Null Values in Chart.js Using Angular

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

Webpack, TypeScript, and modules are set to "esnext," resulting in a change to undefined

In my setup, I am using webpack with typescript (via ts-loader). To enable code splitting in webpack, it is necessary to adjust the module setting to esnext in the tsconfig file: // tsconfig.json { "compilerOptions": { "module": ...

chart for visualizing two rows with matching IDs and dates

I have been attempting to accomplish the following two scenarios: 1) When both ID and dates are the same in the chart, but the descriptions differ, I want to display them on separate lines. 2) If there is not enough room to show the row label, I would li ...

I am struggling to make the map method display the specific components I need

Attempting to create a scalable Custom Form using an array of objects and a custom Input field in a React-Typescript project import React, { ChangeEvent } from "react" import { InputField } from "./InputField" interface FormItem { ...

How can I apply unique "compilerOptions" settings to a specific file in tsconfig.json file?

Can I apply specific tsconfig options to just one file? Here is my current tsconfig.json: { ... "compilerOptions": { ... "keyofStringsOnly": false, "resolveJsonModule": true, "esModuleInterop": t ...

Incorporate the pdfmake.js file into my TypeScript file

Working on a VSTS web extension and looking to utilize PDFmake.js to generate a pdf. The PDFmake.js file needs to be imported into the node_nodules folder by running npm install pdfmake. To import this JavaScript file into my TypeScript file, I'm fol ...

Ways to eliminate angular-fontawesome from a project?

I initially added Angular fontawesome to my project using the command provided in this link: https://www.npmjs.com/package/@fortawesome/angular-fontawesome ng add @fortawesome/angular-fontawesome@6 However, I have now decided that I want to switch to Font ...

The most efficient method for receiving real-time updates from the server to the app is through Angular 7

Currently, I am in the process of developing an Angular 7 messages service (user to user) for my website. The approach I have taken involves receiving updates from the server (Yii2 REST API) every 3 minutes using an interval function (see code snippet belo ...

Can Angular components be used to replace a segment of a string?

Looking to integrate a tag system in Angular similar to Instagram or Twitter. Unsure of the correct approach for this task. Consider a string like: Hello #xyz how are you doing?. I aim to replace #xyz with <tag-component [input]="xyz">&l ...

Vue: Storing selected list values in an array

I am working on a Vue application where I need to select two elements from a list component and place them inside an array. Currently, I have my list set up with selection functionality thanks to Vuetify. I have bound the selected items to an array using v ...

The background image causes the scrollbar to vanish

As a beginner, I am in the process of creating a web page that features a consistent background image. However, I have encountered an issue where the scroll bar does not appear on a specific page called "family details" due to the background image. I atte ...

Exploring the power of Javascript for number lookup

I am currently working on a coding project using TypeScript and JavaScript to locate a specific number provided by the user within a list. The goal is to display whether or not the number is present in the list when the 'search' button is pressed ...

Issue with Dropdown menu in Navbar on Bootstrap 5 when using ng add installation technique

Here's my current setup: I'm currently using Angular 11.2.11 and Bootstrap 5 on a Windows system. The project I'm working on utilizes SCSS. The Issue at Hand: I've been following the codes provided in the bootstrap documentation (whi ...

Stream in Node.js seems to have frozen

I am looking to develop a basic csv parser using the csv module and effectively handle errors when the file is missing. If I remove the sleep functions, the code successfully reaches the Finally statement (and produces an error output). What am I overloo ...

ng2-order-pipe fails to apply sorting when objects are added or removed

I have set up my application to display a div for each object in an array, utilizing the ng2-order-pipe to arrange them accordingly: <div class="patients-container" (dragover)="allowDrop($event)" (drop)="onDrop($event)"> <div class="patient-box ...

Leveraging ES Module packages in Azure TypeScript Function Development

I'm encountering an issue while trying to utilize the p-map package in my Azure Function. The error message that I'm getting is as follows: A Worker failed to load function: 'serverless' with function id: '<id>'. Result: ...

I am working on two Angular projects and I am looking to integrate one of them into the other project

In my development work, I am juggling two Angular projects on Github: AngularApp1 and AngularApp2. AngularApp1 is a robust project with many components, while AngularApp2 serves a more specific purpose. My goal is to have a button in AngularApp1 that open ...

The TS2583 error in TypeScript occurs when it cannot locate the name 'Set' within the code

Just started my Typescript journey today and encountered 11 errors when running tsc app.ts. Decided to tackle them one by one, starting with the first. I tried updating tsconfig.json but it seems like the issue lies within node_modules directory. Any help ...

Is there a feature in Angular similar to Vue.js's "computed property" functionality?

After mastering Vue.js, I recently dove into Angular 4 for a new project. I've found that most things in Angular are quite similar to Vue, with the notable exception of "Computed Property". In Vue, I could easily create a computed property that would ...

NextJS applications can encounter issues with Jest's inability to parse SVG images

Upon running yarn test, an unexpected token error is encountered: Jest encountered an unexpected token This typically indicates that Jest is unable to parse the file being imported, suggesting it's not standard JavaScript. By default, Jest will use ...

Encountering errors while running Angular 8's ng build prod command

After successfully migrating my project from Angular 7 to Angular 8, I encountered an issue when attempting to run 'ng build prod' which resulted in the following error: ERROR in Error during template compile of 'Ng2CompleterModule' Cou ...