ng2-charts Documentation

repository·master·Indexed 25 days ago

https://github.com/valor-software/ng2-charts

A library providing chart components for Angular applications, built on top of Chart.js. It features the BaseChartDirective for rendering various chart types (line, bar, radar, pie, polarArea, doughnut, bubble, and scatter), a ThemeService for dynamic color overrides, and a provideCharts configuration utility for standalone components or AppModules. The library includes support for Angular CLI installation via schematics and provides methods for dataset visibility control and exporting charts to Base64 images.

Tokens
3.6K
Snippets
7
Records
24
Agent score
72%

What's inside ng2-charts

  1. Implement Dynamic Theming with ThemeService

    master

    The ThemeService allows you to apply color overrides to charts when a theme changes. You can pass a ChartOptions object to setColorschemesOptions().

    Override Behavior:

    • Simple fields: Replaces the matching field in the chart's options object.
    • Arrays: If an array is encountered (e.g., xAxes or yAxes), the single object provided in the override acts as a template to update all elements within that array.
    type Theme = 'light-theme' | 'dark-theme';
    
    private _selectedTheme: Theme = 'light-theme';
    public get selectedTheme() {
      return this._selectedTheme;
    }
    
    public set selectedTheme(value: Theme) {
      this._selectedTheme = value;
      let overrides: ChartOptions;
      if (this.selectedTheme === 'dark-theme') {
        overrides = {
          legend: {
            labels: { fontColor: 'white' }
          },
          scales: {
            xAxes: [{ 
              ticks: { fontColor: 'white' },
              gridLines: { color: 'rgba(255,255,255,0.1)' }
            }],
            yAxes: [{ 
              ticks: { fontColor: 'white' },
              gridLines: { color: 'rgba(255,255,255,0.1)' }
            }]
          }
        };
      } else {
        overrides = {};
      }
      this.themeService.setColorschemesOptions(overrides);
    }
    
    constructor(private themeService: ThemeService<AppChartMetaConfig)) {}
    
    setCurrentTheme(theme: Theme) {
      this.selectedTheme = theme;
    }
  2. Manual installation of ng2-charts and Chart.js

    master

    If you prefer manual installation, follow these steps:

    1. Install ng2-charts using your preferred package manager:
      npm install ng2-charts --save

    or

    yarn add ng2-charts --save

    
    2. Install `chart.js` (a required peer dependency):
       ```bash
    npm install chart.js --save
    # or
    yarn add chart.js --save
    npm install ng2-charts --save
    yarn add ng2-charts --save
    npm install chart.js --save
    yarn add chart.js --save
  3. Configure ng2-charts in Standalone Components or AppModule

    master

    After manual installation, you must import the BaseChartDirective and provide the chart configuration.

    For Standalone Components

    Import BaseChartDirective into your component's imports array and use provideCharts in your application bootstrap.

    import { BaseChartDirective, provideCharts, withDefaultRegisterables } from 'ng2-charts';
    
    @Component({
      standalone: true,
      imports: [BaseChartDirective],
      // ...
    })
    export class MyComponent {}
    
    // In main.ts
    bootstrapApplication(AppComponent, {
      providers: [provideCharts(withDefaultRegisterables())],
    }).catch((err) => console.error(err));

    For AppModule

    Include provideCharts in the providers array of your @NgModule.

    import { provideCharts, withDefaultRegisterables } from 'ng2-charts';
    
    @NgModule({
      providers: [provideCharts(withDefaultRegisterables())],
      bootstrap: [AppComponent],
    })
    export class AppModule {}

    Custom Configuration (Bundle Size Optimization)

    To reduce bundle size, you can provide only the specific registerables you need instead of using withDefaultRegisterables():

    provideCharts({ registerables: [BarController, Legend, Colors] });
    import { BaseChartDirective } from 'ng2-charts';
    
    @Component({
      standalone: true,
      imports: [BaseChartDirective],
    })
    export class MyComponent {}
    
    import { provideCharts, withDefaultRegisterables } from 'ng2-charts';
    
    bootstrapApplication(AppComponent, {
      providers: [provideCharts(withDefaultRegisterables())],
    }).catch((err) => console.error(err));
  4. Install ng2-charts using Angular CLI

    master

    The easiest way to install ng2-charts is via the Angular CLI. This command automatically installs the required packages and updates your app.config.ts with the necessary configuration to start using the library immediately.

    ng add ng2-charts
  5. Use the baseChart directive to render charts

    master

    The baseChart directive is applied to a <canvas> element to render Chart.js charts within an Angular application. It is a standalone directive that can be exported as base-chart for template reference.

    To use it, apply the baseChart attribute to a canvas element and provide the necessary chart configuration via inputs like type, data, and options.

  6. Install ng2-charts using Angular schematics

    master

    You can automatically set up ng2-charts and its required dependency chart.js in your Angular project using the ng add command. This schematic performs the following actions:

    1. Adds ng2-charts (version ^9.0.0) to your package.json.
    2. Adds chart.js (version ^4.3.0) to your package.json.
    3. Runs the ng-add-setup-project schematic to complete the integration.
    4. Triggers a package installation (e.g., npm install or yarn install).

    If you specify a project name via the --project option, the schematic will verify that the project exists in your workspace before proceeding.

  7. Configure the ng2-charts provider in Angular

    master

    When using standalone Angular applications, you must provide the ng2-charts configuration in your application config (typically app.config.ts). This is done by calling provideCharts() and passing withDefaultRegisterables() to ensure all standard Chart.js components are registered.

    If you use the ng add ng2-charts schematic, this step is performed automatically. If configuring manually, use the following pattern in your providers array.

  8. Reference: baseChart events

    master

    The baseChart directive emits the following events:

    • chartClick: Fires when a click occurs on the chart. Returns information regarding active points and labels.
    • chartHover: Fires when a mousemove (hover) occurs on the chart. Returns information regarding active points and labels.
  9. Reference: baseChart properties

    master

    The following properties are available on the baseChart directive:

    • type (ChartType): Indicates the type of chart (e.g., line, bar, radar, pie, polarArea, doughnut, or custom types).
    • data (ChartData<TType, TData, TLabel>): The complete data structure to be rendered. Supports flexible formats or individual labels and datasets properties.
    • labels (TLabel[]): Dataset labels. Required for line, bar, and radar. Used for hover labels in polarArea, pie, and doughnut.
    • datasets (ChartDataset<TType, TData>[]): The datasets configuration, matching the datasets property of the data input.
    • options (ChartOptions<TType>): Chart configuration options (refer to Chart.js documentation).
    • legend (boolean = false): If set to true, the chart legend is displayed.