Search code examples
htmlcssangulargoogle-visualization

Set google chart width to 100% on page resize in angular 4+


I have an app with many wrappers responsive to the site (A bunch of div's predefined from an API), those are filled with a google chart each. Issue is, when the page first loads the charts are rendered to the current size, and when window is resized only the wrappers change, not the charts itself.

How can I make something like this https://codepen.io/flopreynat/pen/BfLkA without using Jquery and would this need to be set in a particular life-cycle in Angular (e.g. onChange?) or just a function? I am using a library that just retrieves data, so I don't have functions as this:

$(window).resize(function(){
  drawChart1();
  drawChart2();
});

Solution

  • Here's how you bind window:resize in Angular 4+:

    import {ElementRef, HostListener, ViewChild} from '@angular/core';
    import {GoogleChartComponent} from 'ng2-google-charts';
    
    ...
    
    export class YourChart {
      @ViewChild('chart') chart: GoogleChartComponent;
      ...
      @HostListener('window:resize', ['$event'])
      onWindowResize(event: any) {
        let selection = this.chart.wrapper.visualization.getSelection();
        this.chart.redraw();
        this.chart.wrapper.visualization.setSelection(selection);
        // you can remove two lines that preserve selection if you don't need them
      }
    }