Skip to content
Tutorials Center
My learning

Topics

Lesson 59 of 74 ยท Tooling and Ecosystem

Using Third-Party JavaScript Libraries (Chart.js, jQuery) in Angular

Wrap non-Angular libraries such as Chart.js or jQuery in a component with viewChild, afterNextRender, effect and runOutsideAngular, add types, and clean up, with runnable stand-ins.

Angular does not have to replace every library you know. Charting libraries, map widgets, rich-text editors, date pickers and even old jQuery plugins work fine in an Angular app. The only question is how to plug them in so that they respect Angular's rules: they need a real DOM element, they must be created at the right moment, updated when data changes, and destroyed when the component goes away.

The recipe is always the same: install the library and its types, wrap it in one component that hides the library from the rest of the app, and give that component a clean input()/output() API. In this lesson you will build such a wrapper for Chart.js and then see how the same idea applies to jQuery plugins. You should know view queries, signals in components and the component lifecycle.

Real versus stand-in. The bash, typescript and html blocks are real code to read; the site cannot compile Angular or load Chart.js in an Angular app. The runnable examples are stand-ins in plain TypeScript: a fake chart library with a create/update/destroy API, a fake zone that counts change-detection runs, and the wrapper's lifecycle rules. They show the logic, not the real libraries.

Step 1: install the library and its types

Terminal
npm install chart.js

Chart.js ships its own TypeScript types. Many older libraries do not; for those, install the community types as a dev dependency (npm install --save-dev @types/jquery, @types/lodash, and so on). If a library has no types at all, write a tiny declaration file so the rest of your code stays type-checked:

TypeScript
// src/types/legacy-widget.d.ts
declare module 'legacy-widget' {
  export function init(element: HTMLElement, options?: { color?: string }): { destroy(): void };
}

Libraries that you load with a plain <script> tag (a CDN build, for instance) can be listed under scripts in angular.json. Prefer npm packages: the bundler then removes unused code and you get lockfile control.

Step 2: wait for the DOM, then create the instance

Most libraries need a real element, such as a <canvas>. In a component that element exists only after the first render, so you cannot create the chart in the constructor. Get the element with viewChild() and create the chart inside afterNextRender(), which runs once, in the browser only, after Angular has rendered the component:

TypeScript
// sales-chart.ts
import {
  afterNextRender,
  ChangeDetectionStrategy,
  Component,
  DestroyRef,
  effect,
  ElementRef,
  inject,
  input,
  NgZone,
  viewChild,
} from '@angular/core';
import { Chart, ChartConfiguration, registerables } from 'chart.js';

Chart.register(...registerables);

@Component({
  selector: 'app-sales-chart',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `<canvas #canvas role="img" [attr.aria-label]="label()"></canvas>`,
})
export class SalesChart {
  readonly labels = input.required<string[]>();
  readonly values = input.required<number[]>();
  readonly label = input('Sales per month');

  private readonly canvas = viewChild.required<ElementRef<HTMLCanvasElement>>('canvas');
  private readonly zone = inject(NgZone);
  private chart?: Chart;

  constructor() {
    const destroyRef = inject(DestroyRef);

    afterNextRender(() => {
      // Chart.js attaches many listeners (resize, mouse, animation frames).
      // Keep them out of Angular's change detection.
      this.zone.runOutsideAngular(() => {
        this.chart = new Chart(this.canvas().nativeElement, this.buildConfig());
      });
    });

    // Re-run whenever an input signal changes, but only once the chart exists
    effect(() => {
      const labels = this.labels();
      const values = this.values();
      if (!this.chart) return;
      this.chart.data.labels = labels;
      this.chart.data.datasets[0].data = values;
      this.chart.update();
    });

    destroyRef.onDestroy(() => this.chart?.destroy());
  }

  private buildConfig(): ChartConfiguration<'bar'> {
    return {
      type: 'bar',
      data: {
        labels: this.labels(),
        datasets: [{ label: this.label(), data: this.values() }],
      },
      options: { responsive: true, animation: { duration: 300 } },
    };
  }
}

Use it like any component:

HTML
<app-sales-chart [labels]="months()" [values]="sales()" />

Four rules are visible here:

  • Create after render. afterNextRender() does not run on the server, so server-side rendering (SSR and Hydration) never touches canvas or window.
  • Update through signals. Inputs are signals, so an effect() that reads them re-runs when they change. Mutate the library's own data structures and call its update method; do not recreate the chart.
  • Always destroy. DestroyRef.onDestroy() frees listeners and canvas memory. Forgetting it is the classic leak when users navigate back and forth.
  • Hide the library. Other components pass plain arrays. If you later swap Chart.js for another library, only this file changes.

An effect that reads a signal and touches a non-Angular object is fine. Just keep signal reads at the top, as shown, so it is obvious which values the effect depends on (Signals: signal, computed and effect).

Why runOutsideAngular

With Zone.js, every browser event or timer callback ends with an Angular change-detection run. A chart library may listen to mousemove and run an animation loop at 60 frames per second. Each of those callbacks would make Angular check the component tree, even though nothing Angular cares about changed.

NgZone.runOutsideAngular() runs a function without that automatic notification. Code that does need to tell Angular something calls zone.run() (or sets a signal, which notifies Angular by itself). Apps without Zone.js (zoneless) do not need this, but the code stays valid either way.

Calling back into Angular

Libraries report events through callbacks, for example a click on a bar. Convert them into an output():

TypeScript
readonly barClick = output<number>();

// inside buildConfig()
options: {
  onClick: (_event, elements) => {
    const index = elements[0]?.index;
    if (index !== undefined) {
      this.zone.run(() => this.barClick.emit(index)); // back inside Angular
    }
  },
},

The parent now writes (barClick)="select($event)" and never learns that Chart.js exists.

Stand-in: lifecycle and zone cost

The first stand-in has a fake chart class and a fake zone. It shows the wrapper rules: create once after render, update instead of recreating, destroy at the end, and the number of change-detection runs with and without runOutsideAngular.

TypeScript Wrapping a library: create, update, destroy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The wrapper ignores the early effect run, creates the library object once, updates it in place and destroys it, leaving zero live charts. The second half is a model, not a measurement: with Zone.js, a listener registered inside the zone triggers a check on every event, while a listener registered outside triggers none.

jQuery and other DOM-mutating plugins

jQuery plugins work by finding elements and changing the DOM directly. That is the opposite of Angular's style, so keep their reach small:

TypeScript
import $ from 'jquery';
import 'select2'; // hypothetical plugin that decorates a <select>

@Component({
  selector: 'app-fancy-select',
  template: `<select #box><option>One</option><option>Two</option></select>`,
})
export class FancySelect {
  readonly changed = output<string>();
  private readonly box = viewChild.required<ElementRef<HTMLSelectElement>>('box');

  constructor() {
    afterNextRender(() => {
      const $el = $(this.box().nativeElement);
      $el.select2();
      $el.on('change', () => this.changed.emit(String($el.val())));
      inject(DestroyRef).onDestroy(() => {
        $el.off('change');
        $el.select2('destroy');
      });
    });
  }
}

Three habits keep this safe. Select elements with viewChild() and pass the native element instead of querying the whole document with $('.something'). Never let a plugin modify nodes that an Angular template also controls (for example, inside an @for), because Angular would then try to update nodes that no longer match. And remove handlers and destroy the plugin in onDestroy.

Before adding jQuery to a new project, check whether a native browser API or an Angular alternative already does the job; jQuery also adds weight to your bundle. For old plugins you cannot replace, this wrapper pattern is the way to contain them.

When the library needs window or document

Some packages touch window when they are imported, which crashes server rendering. Load them lazily inside afterNextRender():

TypeScript
afterNextRender(async () => {
  const { default: Editor } = await import('heavy-editor');
  this.editor = new Editor(this.host().nativeElement);
});

A dynamic import() also keeps the library out of your main bundle until the component is shown, which helps performance.

Stand-in: loading a library lazily and exactly once

When several components need the same heavy library, share one loading promise. This stand-in models the loader and shows that two components trigger only one load.

TypeScript Lazy loader that loads a library once

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is a chart usually created inside afterNextRender() rather than the constructor?

    The template has not been rendered when the constructor runs. afterNextRender() runs after rendering and never during server rendering.
  2. 2. What does NgZone.runOutsideAngular() do?

    Frequent events from a library, such as mouse moves and animation frames, would otherwise cause Angular to check the tree each time.
  3. 3. What must the wrapper do when the component is destroyed?

    Libraries keep listeners, timers and memory. Without cleanup, navigating back and forth leaks resources.
  4. 4. A library has no TypeScript types. What is a good fix?

    A declaration file keeps type checking for the rest of your code and documents what you use from the library.

Summary

  • Wrap each third-party library in one component with plain input() and output() APIs.
  • Install the library and types from npm; write a declare module file when no types exist.
  • Get the element with viewChild(), create the instance in afterNextRender(), update it from an effect(), and destroy it in DestroyRef.onDestroy().
  • Use NgZone.runOutsideAngular() for chatty listeners and zone.run() (or an output()) to report results back.
  • Contain jQuery plugins to elements you pass in, and load browser-only libraries lazily with import().
  • The Angular and library code is read-only; the fake chart, zone and loader here are stand-ins.

Next: Build and Deploy