Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk6 min

Create Charts in an Angular 7 Application Using Chart.js 2.9.4

A reproducible Angular 7 and Chart.js tutorial using the pinned 2.9.4 API, a reusable canvas component, API data mapping, responsive options, cleanup, and failure fixes.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For an existing Angular 7 application, install the legacy Chart.js 2.9.4 package and create the chart in ngAfterViewInit against a canvas obtained with @ViewChild. Pinning the package matters: the current Chart.js release is 4.5.1, whose imports, registration, scales, and plugin options are different from the 2.x API used here. See the Chart.js version list and the 2.9.4 documentation.

Choose the legacy Angular 7 path

This tutorial targets an NgModule-based Angular 7 project, the TypeScript version already used by that project, and Chart.js 2.9.4. Angular 7 is a legacy framework release; use this combination to maintain an existing application rather than to start a new one.

Chart.js draws onto an HTML5 <canvas>. Angular supplies the component, template, lifecycle, and HTTP services. An optional wrapper such as ng2-charts adds Angular bindings, but direct Chart.js is the smallest and clearest solution for one or two charts.

Prerequisites

  • An existing Angular 7 application and a Node.js/npm toolchain compatible with it.
  • Basic Angular components, TypeScript, and templates.
  • A browser with canvas support.
  • An API endpoint only if your data is remote. Visual Studio, SQL Server, Entity Framework, and an ASP.NET Web API are not required for a local chart; they are backend choices in some older tutorials (source tutorial).

Install and verify Chart.js 2.9.4

In the Angular 7 project directory run:

npm install [email protected]
npm list chart.js
ng version

npm install chart.js now selects the current package. Do not use that unpinned command with the 2.x code below. If you are creating a historical sample from scratch, use a matching Angular CLI rather than running a modern CLI and assuming it produced Angular 7:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
  • WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
  • A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents
ng new chartjsdemo
cd chartjsdemo
npm install [email protected]
ng serve

Build one reusable chart component

Generate the component

ng generate component chart

Template and sizing

Give each component its own canvas reference. Do not repeat a global id="canvas" when several charts can be rendered on one page.

<div class="chart-container">
  <canvas #chartCanvas></canvas>
</div>
.chart-container {
  position: relative;
  width: 100%;
  height: 320px;
}

A responsive canvas still needs a parent with a real height. Without one, percentage-based sizing can collapse or produce unexpected dimensions.

Component class with a bar chart

import {
  AfterViewInit,
  Component,
  ElementRef,
  OnDestroy,
  ViewChild
} from '@angular/core';
import { Chart } from 'chart.js';

@Component({
  selector: 'app-chart',
  templateUrl: './chart.component.html',
  styleUrls: ['./chart.component.css']
})
export class ChartComponent implements AfterViewInit, OnDestroy {
  @ViewChild('chartCanvas') chartCanvas: ElementRef;
  private chart: Chart;

  ngAfterViewInit(): void {
    const context = this.chartCanvas.nativeElement.getContext('2d');

    this.chart = new Chart(context, {
      type: 'bar',
      data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green'],
        datasets: [{
          label: 'Votes',
          data: [12, 19, 3, 5],
          backgroundColor: ['#f44336', '#2196f3', '#ffeb3b', '#4caf50'],
          borderWidth: 1
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        legend: {
          display: true,
          position: 'bottom'
        },
        tooltips: {
          enabled: true
        },
        scales: {
          xAxes: [{
            display: true
          }],
          yAxes: [{
            ticks: {
              beginAtZero: true
            }
          }]
        }
      }
    });
  }

  ngOnDestroy(): void {
    if (this.chart) {
      this.chart.destroy();
    }
  }
}

AfterViewInit runs after Angular has created the canvas; OnInit can run too early. Destroying the instance removes event handlers and releases chart resources when a route or component is replaced.

Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
  • SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors

Use typed data instead of strings

Keep labels and values separate, and keep numerical values numeric. String values can produce type inconsistencies and incorrect scale behavior.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
export interface ChartPoint {
  label: string;
  value: number;
}

points: ChartPoint[] = [
  { label: 'January', value: 42 },
  { label: 'February', value: 58 },
  { label: 'March', value: 71 }
];

const labels = this.points.map(point => point.label);
const values = this.points.map(point => point.value);

Change the chart type

For the same labels and dataset, change the type and add options appropriate to the visual question:

Type Best use Typical data shape
bar Compare categories One value per label
line Show a trend over ordered periods Values aligned to dates or sequence labels
pie Parts of one whole One dataset whose values sum to a meaningful total
doughnut Parts of a whole with a central hole Same as pie
polarArea Radial comparison of categories One value per category
radar Compare several dimensions Values on shared named axes
bubble Three numeric dimensions {x, y, r} points
scatter Relationship between two numeric variables {x, y} points

Line chart

type: 'line',
datasets: [{
  label: 'Runs',
  data: values,
  borderColor: '#3cb371',
  backgroundColor: 'rgba(60, 179, 113, 0.2)',
  fill: true
}]

For pie, doughnut, and polar-area charts, use the corresponding type and usually one dataset with a color per value. Keep category labels short and ensure the values represent a meaningful whole before choosing pie or doughnut.

Rank #3
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
  • Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
  • Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
  • In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
  • Ultra-thin bezels: Maximize your viewing experience with thin bezels.

Load chart data from an API

Enable HttpClient

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    BrowserModule,
    HttpClientModule
  ]
})
export class AppModule {}

Create a typed service

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

export interface PlayerStat {
  PlayerName: string;
  Run: number;
}

@Injectable()
export class ChartDataService {
  constructor(private http: HttpClient) {}

  getPlayerStats(): Observable<PlayerStat[]> {
    return this.http.get<PlayerStat[]>('/api/charts');
  }
}

Use a same-origin URL where possible, or configure an Angular development proxy. Validate the response before rendering: require an array, reject null records, convert numeric strings deliberately, and handle an empty result separately from an error.

Render after the response and replace safely

private renderChart(labels: string[], values: number[]): void {
  if (this.chart) {
    this.chart.destroy();
  }

  const context = this.chartCanvas.nativeElement.getContext('2d');

  this.chart = new Chart(context, {
    type: 'line',
    data: {
      labels,
      datasets: [{
        label: 'Runs',
        data: values,
        borderColor: '#3cb371',
        backgroundColor: 'rgba(60, 179, 113, 0.2)',
        fill: true
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false
    }
  });
}

Call this method from the subscription after mapping the API response. Track loading, empty, and error states in the template, and do not append to label or value arrays on every emission without clearing or replacing them.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Direct Chart.js or ng2-charts?

Direct Chart.js has fewer dependencies, exposes the complete configuration object, and is straightforward for a small number of charts. Its trade-off is manual canvas access, updates, and cleanup.

Rank #4
Sale
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
  • SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
  • MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
  • KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
  • INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient

ng2-charts supplies Angular directives and bindings, which can reduce repetitive lifecycle code in a larger application. Wrapper APIs and peer dependencies change independently of Chart.js. The published compatibility information for ng2-charts 5.0.4 places Angular 2–9 on its v1.x line; do not install the current wrapper blindly in Angular 7. The project’s compatibility table is maintained in its repository.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot the common failures

Module not found

Run npm install [email protected], check npm list chart.js, and restart ng serve.

“Chart is not a constructor” or import errors

Check for a major-version mismatch or code copied from Chart.js 3/4. Either pin 2.9.4 for this API or rewrite for the modern API; do not mix them.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
  • 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
  • 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.

“getContext of null”

Create the chart in ngAfterViewInit, use the component’s @ViewChild reference, and confirm the template has rendered. Duplicate IDs and incorrect selectors are common causes.

Blank chart

  • Confirm the container has a visible height.
  • Ensure labels and data arrays align.
  • Ensure dataset values are numbers and the type is spelled correctly.
  • Inspect the browser console and the actual API response.

Duplicate charts or repeated rendering

Destroy the previous instance before creating another and avoid pushing the same response into arrays on every observable emission.

CORS errors

The old tutorial demonstrates wildcard CORS with * (example). That can be acceptable for a local demonstration, but production APIs should restrict origins, methods, and headers. Prefer same-origin hosting or a development proxy.

Server-side rendering

Chart.js requires a browser canvas. Defer construction until browser execution and guard access to window, document, and the canvas when using Angular Universal or another pre-rendering setup.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Accessibility and production checks

  • Give the chart a visible title and a text summary of the important result.
  • Offer an accessible data table or downloadable data; canvas pixels are not a complete text alternative.
  • Use sufficient contrast and do not communicate categories by color alone.
  • Keep API validation and transport concerns in services rather than embedding database details in the chart component.

If you are starting a project today

Upgrade Angular instead of beginning a new Angular 7 application. Current Chart.js documentation uses registration for controllers, elements, scales, and plugins, or the convenience import chart.js/auto (integration guide). Its installation command is npm install chart.js (installation guide), but those current examples and option paths are not interchangeable with the Chart.js 2.9.4 code in this article.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.