Skip to content
Projetos

FERNman/angular-google-charts

Ver no GitHub

Sobre

A wrapper for the Google Charts library written in Angular.

Desenvolvimento web e de aplicativos

Como estes números são medidos

Crescimento medido de estrelas

em 24 h
0
em 7 dias
+1
em 15 dias
+1
em 1 mês
Coletando histórico

Variações líquidas em períodos sobrepostos, não totais diários. Medições ausentes ficam em branco. Estrelas indicam interesse, não qualidade.

README.md

Original

Angular Google Charts

npm GitHub Actions Workflow Status License: MIT styled with prettier

The most popular wrapper of the Google Charts library for Angular.

Overview

  • Composable: Declarative components enable creating simple charts all the way to complex dashboards easily 💛
  • Standalone-First & signals: Modern Angular with fine-grained reactivity and tree shaking 🚀
  • Compatible with SSR: Plug into any app without issues ✅

Package Version Compatibility

We always aim to support the current Angular LTS versions.

Angular Version Library Version Maintenance Standalone Components
>= 21.0.0 < 23.0.0 21.x ✅ Active Support ✅ Available
>= 16.0.0 < 21.0.0 16.1.x ❌ Not Maintained ✅ Available (16.1.x)

Upgrading from 16.x? See what changed in 21.x.


Quick Start 🚀

Installation

npm install angular-google-charts

Setup

Import the components you need and use them in your templates. No providers are required:

// app.component.ts
import { Component } from '@angular/core';
import { ChartType, GoogleChartComponent } from 'angular-google-charts';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [GoogleChartComponent],
  template: `
    <h1>My Dashboard</h1>
    <google-chart
      type="PieChart"
      [data]="pieChartData"
      [columns]="pieChartColumns"
      [options]="pieChartOptions"
      [width]="500"
      [height]="400"
    >
    </google-chart>
  `
})
export class AppComponent {
  pieChartData = [
    ['Work', 11],
    ['Eat', 2],
    ['Commute', 2],
    ['Watch TV', 2],
    ['Sleep', 7]
  ];

  pieChartColumns = ['Task', 'Hours per Day'];

  pieChartOptions = {
    title: 'My Daily Activities',
    pieHole: 0.4
  };
}

Configuration

To change the defaults, configure Google Charts globally with provideGoogleCharts:

// main.ts
bootstrapApplication(AppComponent, {
  providers: [
    provideGoogleCharts({
      version: '49',
      mapsApiKey: 'your-api-key'
    })
  ]
});

Available Components

The core library is made up of the following components:

  • GoogleChartComponent - Main chart component (usually you start here)
  • ChartWrapperComponent - 1:1 wrapper for Google's ChartWrapper (if you need "raw" library access)
  • DashboardComponent - Dashboard container with controls
  • ControlWrapperComponent - Interactive chart controls
  • ChartEditorComponent - Chart editing interface

Usage Examples

Basic Chart:

import { GoogleChartComponent } from 'angular-google-charts';

@Component({
  standalone: true,
  imports: [GoogleChartComponent],
  template: `<google-chart [type]="type" [data]="data"></google-chart>`
})

Dashboard with Controls:

import { ControlWrapperComponent, DashboardComponent, GoogleChartComponent } from 'angular-google-charts';

@Component({
  standalone: true,
  imports: [DashboardComponent, ControlWrapperComponent, GoogleChartComponent],
  template: `
    <dashboard [data]="dashboardData" [columns]="dashboardColumns">
      <control-wrapper [for]="myChart" type="CategoryFilter" [options]="{ filterColumnIndex: 0 }"></control-wrapper>
      <google-chart #myChart type="ColumnChart"></google-chart>
    </dashboard>
  `
})

Chart Types & Properties

Supported Chart Types

All Google Charts types are supported. Check the ChartType file for the complete list or visit the Google Charts Gallery.

Component Properties

Essential Properties

Property Type Description
[type] ChartType Required. Chart type (e.g., 'PieChart', 'BarChart')
[data] any[][] Required. Chart data as 2D array
[columns] string[] | object[] Column definitions
[options] object Chart-specific options

Optional Properties

Property Type Description
[title] string Chart title
[width] number Width in pixels
[height] number Height in pixels
[formatters] Formatter[] Data formatters
[dynamicResize] boolean Redraw when the chart's element is resized

Data Format

// Simple data format
myData = [
  ['London', 8136000],
  ['New York', 8538000],
  ['Paris', 2244000],
  ['Berlin', 3470000]
];

// With custom formatting
myData = [
  ['London', { v: 8136000, f: '8.14M' }],
  ['New York', { v: 8538000, f: '8.54M' }]
];

Chart Options

Customize charts with Google Charts options:

myOptions = {
  title: 'Population by City',
  colors: ['#e0440e', '#e6693e', '#ec8f6e'],
  is3D: true,
  pieHole: 0.4,
  legend: { position: 'bottom' }
};

Events

All chart events are supported:

@Component({
  template: `
    <google-chart
      (ready)="onChartReady($event)"
      (select)="onChartSelect($event)"
      (error)="onChartError($event)"
      (chartMouseOver)="onMouseOver($event)"
      (chartMouseLeave)="onMouseLeave($event)"
    >
    </google-chart>
  `
})
export class MyComponent {
  onChartReady(event: ChartReadyEvent) {
    console.log('Chart ready:', event);
  }

  onChartSelect(event: ChartSelectionChangedEvent) {
    console.log('Selection changed:', event.selection);
  }
}

Interactive Dashboards

Create powerful dashboards with multiple charts and controls:

@Component({
  standalone: true,
  imports: [DashboardComponent, ControlWrapperComponent, GoogleChartComponent],
  template: `
    <dashboard [data]="salesData" [columns]="salesColumns">
      <!-- Date range filter -->
      <control-wrapper [for]="[salesChart, regionChart]" type="DateRangeFilter" [options]="dateFilterOptions">
      </control-wrapper>

      <!-- Category filter -->
      <control-wrapper [for]="salesChart" type="CategoryFilter" [options]="categoryFilterOptions"> </control-wrapper>

      <!-- Charts controlled by filters -->
      <google-chart #salesChart type="LineChart"></google-chart>
      <google-chart #regionChart type="GeoChart"></google-chart>
    </dashboard>
  `
})
export class SalesDashboard {
  salesData = [
    ['Date', 'Region', 'Sales'],
    [new Date(2024, 0, 1), 'North', 1000],
    [new Date(2024, 0, 2), 'South', 1200]
    // ... more data
  ];
}

Chart Editor

Enable users to customize charts with the built-in editor:

import { Component, ViewChild } from '@angular/core';
import { ChartEditorComponent, GoogleChartComponent } from 'angular-google-charts';

@Component({
  standalone: true,
  imports: [ChartEditorComponent, GoogleChartComponent],
  template: `
    <chart-editor></chart-editor>
    <google-chart #myChart [type]="chartType" [data]="chartData"></google-chart>
    <button (click)="editChart()">Edit Chart</button>
  `
})
export class EditableChart {
  @ViewChild(ChartEditorComponent) editor!: ChartEditorComponent;
  @ViewChild('myChart') chart!: GoogleChartComponent;

  editChart() {
    this.editor
      .editChart(this.chart)
      .afterClosed()
      .subscribe(result => {
        if (result) {
          console.log('Chart updated!');
        }
      });
  }
}

Advanced Usage

Global Configuration

provideGoogleCharts({
  version: '49', // Google Charts version
  mapsApiKey: 'API_KEY', // For GeoChart and Maps
  safeMode: true // Enable safe mode (Charts 47+)
});

Using ScriptLoaderService

For custom implementations:

import { Component, ViewChild, ElementRef, OnInit } from '@angular/core';
import { ScriptLoaderService } from 'angular-google-charts';

@Component({
  standalone: true,
  template: `<div #chartContainer></div>`
})
export class CustomChart implements OnInit {
  @ViewChild('chartContainer', { static: true })
  container!: ElementRef;

  constructor(private loader: ScriptLoaderService) {}

  ngOnInit() {
    this.loader.loadChartPackages('corechart').subscribe(() => {
      const chart = new google.visualization.PieChart(this.container.nativeElement);
      chart.draw(this.createDataTable(), this.getOptions());
    });
  }
}

or with a dynamically loaded configuration (example):

// service
@Injectable({ providedIn: 'root' })
export class ConfigService {
  private configSubject = new ReplaySubject<GoogleChartsConfig>(1);
  config$ = this.configSubject.asObservable();

  updateConfig(config: GoogleChartsConfig) {
    this.configSubject.next(config);
  }
}

// main.ts
bootstrapApplication(AppComponent, {
  providers: [
    {
      provide: GOOGLE_CHARTS_LAZY_CONFIG,
      useFactory: (service: ConfigService) => service.config$,
      deps: [ConfigService]
    }
  ]
});

Custom Chart Components

Create reusable chart components:

import { Component, Input } from '@angular/core';
import { GoogleChartComponent } from 'angular-google-charts';

@Component({
  selector: 'sales-chart',
  standalone: true,
  imports: [GoogleChartComponent],
  template: `
    <google-chart type="ComboChart" [data]="processedData" [options]="chartOptions" [width]="width" [height]="height">
    </google-chart>
  `
})
export class SalesChart {
  @Input() salesData: any[] = [];
  @Input() width = 600;
  @Input() height = 400;

  get processedData() {
    // Transform your data here
    return this.salesData;
  }

  get chartOptions() {
    return {
      title: 'Sales Performance',
      vAxes: {
        0: { title: 'Revenue ($)' },
        1: { title: 'Units Sold' }
      },
      series: {
        0: { type: 'columns', targetAxisIndex: 0 },
        1: { type: 'line', targetAxisIndex: 1 }
      }
    };
  }
}

Performance Optimization

Preloading Scripts

If you know you'll show a chart on the first page, preload Google Charts in your index.html:

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js" async></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/49/loader.js" async></script>

Server-Side Rendering

The components are safe to use with server-side rendering. On the server, they render empty host elements and don't load the Google Charts script. loadChartPackages() completes without emitting there. The charts are drawn in the browser once the app has loaded or hydrated.

Upgrading from 16.x

  • Angular 21 or 22 is required.
  • Import the components by their *Component names, e.g. GoogleChartComponent instead of GoogleChart. The old names still work, but are deprecated.
  • Inputs are signals. Templates don't change, but reading an input in code now needs a call, e.g. chart.data() instead of chart.data. Set inputs through templates or componentRef.setInput().
  • Outputs are OutputEmitterRefs instead of EventEmitters. subscribe() still works. For RxJS operators, use outputToObservable(chart.ready) from @angular/core/rxjs-interop.
  • mouseover and mouseleave on <google-chart> are now chartMouseOver and chartMouseLeave, as the old names also received the browser's native mouse events.
  • type is a required input on <google-chart> and <control-wrapper>, as is for on <control-wrapper>. Missing ones are now a compile error instead of a runtime error.

Migration from NgModules

To migrate to standalone components:

1. Replace imports:

// Before
import { GoogleChartsModule } from 'angular-google-charts';

// After
import { GoogleChartComponent } from 'angular-google-charts';

2. Update components:

@Component({
  standalone: true,
  imports: [GoogleChartComponent], // Add specific imports
  // ... rest of component
})

Done!


Traditional NgModule Usage

Note: While NgModule usage is still supported, we recommend using standalone components for new projects.

Click to see NgModule documentation

NgModule Setup

import { GoogleChartsModule } from 'angular-google-charts';

@NgModule({
  imports: [
    GoogleChartsModule,
    // or with configuration
    GoogleChartsModule.forRoot({ version: '49' })
  ],
  declarations: [AppComponent],
  bootstrap: [AppComponent]
})
export class AppModule {}

Using forRoot Configuration

GoogleChartsModule.forRoot({
  version: 'chart-version',
  mapsApiKey: 'your-api-key'
});

Lazy Loading Configuration

Option 1: Service-based

@Injectable()
export class GoogleChartsConfigService {
  private configSubject = new ReplaySubject<GoogleChartsConfig>(1);
  readonly config$ = this.configSubject.asObservable();

  constructor(private http: HttpClient) {}

  loadLazyConfigValues(): void {
    this.http
      .post('https://api.example.com/config', {})
      .pipe(take(1))
      .subscribe(config => this.configSubject.next(config));
  }
}

export function googleChartsConfigFactory(configService: GoogleChartsConfigService): Observable<GoogleChartsConfig> {
  return configService.config$;
}

@NgModule({
  providers: [
    GoogleChartsConfigService,
    {
      provide: GOOGLE_CHARTS_LAZY_CONFIG,
      useFactory: googleChartsConfigFactory,
      deps: [GoogleChartsConfigService]
    }
  ]
})
export class AppModule {}

Option 2: Global Subject

export const googleChartsConfigSubject = new ReplaySubject<GoogleChartsConfig>(1);

// Call this from anywhere
googleChartsConfigSubject.next(config);

@NgModule({
  providers: [
    {
      provide: GOOGLE_CHARTS_LAZY_CONFIG,
      useValue: googleChartsConfigSubject.asObservable()
    }
  ]
})
export class AppModule {}

Important Notes:

  • You can use forRoot() OR GOOGLE_CHARTS_LAZY_CONFIG, not both
  • Lazy-loaded configs delay chart rendering until config is available

License

This project is provided under the MIT license.

Contributing

We welcome contributions!

Support


Like this project? Give it a star on GitHub!

Explore projetos relacionados

Carregando…