我在同一页面/组件上加载了两个图表。我能够让它们在页面加载时显示得很好。我的网站是响应式的,我需要在window.resize上重绘图表。当只有一个图表时,一切正常,但当我向页面添加第二个图表时,只有第二个(最后一个)图表在window.resize上调整大小。我该如何解决这个问题?
我正在使用angular2 rc1,使用angular2-google-chart:“https://www.npmjs.com/package/angular2-google-chart” 在github上:“https://github.com/vimalavinisha/angular2-google-chart”
index.html页面:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script>
/* googleLoaded = false allows for more than one chart per page */
var googleLoaded = false;
</script>
谷歌charts.directive.ts:
import {
Directive,
ElementRef,
Input,
OnInit } from '@angular/core';
declare var google : any;
declare var googleLoaded : any;
@Directive( {
selector: '[GoogleChart]',
properties: [
'chartType',
'chartOptions',
'chartData'
]
} )
export class GoogleChart implements OnInit {
public _element : any;
@Input( 'chartType') public chartType : string;
@Input( 'chartOptions' ) public chartOptions : Object;
@Input( 'chartData' ) public chartData : Object;
constructor( public element: ElementRef ) {
this._element = this.element.nativeElement;
//This is where I resize the charts, but it only resizes the last on on the page????
window.onresize = ( e ) => {
//you need to get all charts on the page somehow
this.drawGraph(
this.chartOptions,
this.chartType,
this.chartData,
this._element
)
}
}
ngOnInit() {
if( !googleLoaded ) {
googleLoaded = true;
google.charts.load( 'current', { 'packages':['corechart', 'gauge'] } );
}
setTimeout(
() => this.drawGraph(
this.chartOptions,
this.chartType,
this.chartData,
this._element
), 500 );
}
drawGraph ( chartOptions, chartType, chartData, ele ) {
google.charts.setOnLoadCallback( drawChart );
function drawChart() {
var wrapper;
wrapper = new google.visualization.ChartWrapper( {
chartType : chartType,
dataTable : chartData ,
options : chartOptions || {},
containerId : ele.id
} );
wrapper.draw();
}
}
}
图表显示的组件:
<div id="bar_chart" class="google-chart"
[chartData]="bar_ChartData"
[chartOptions] = "bar_ChartOptions"
chartType="BarChart"
GoogleChart
></div>
<div id="pie_chart" class="google-chart"
[chartData]="pie_ChartData"
[chartOptions] = "pie_ChartOptions"
chartType="PieChart"
GoogleChart
></div>
我能够为每个图表创建一个不同的指令并使其工作,但根据页面我可能需要使用4或5个不同的图表,它似乎有点多。
tl; dr:我使用带有angular2 rc1的谷歌图表,我会显示多个图表,但是当我调整页面大小时,只有最后一个图表重新绘制自己。如何在同一页面上重新绘制多个图表?