2

I am using zingchart in my angular2 application and came a cross this problem. My data for the chart have changed i need to rerender the chart and I just don't know how to do that? this is the plunkr that the zing chart team provided with my button of rerender. I don't know how to rerender the chart. https://plnkr.co/edit/OjqvVPiyKBUJbKgcLi6A?p=preview

  import {bootstrap} from 'angular2/platform/browser';
import {Component, NgZone, AfterView, OnDestroy} from 'angular2/core'

class Chart { 
  id: String;
  data: Object;
  height: any;
  width: any;
  constructor(config: Object) {
    this.id = config['id'];
    this.data = config['data'];
    this.height = config['height'] || 300;
    this.width = config['width'] || 600;
  }
}

@Component({
  selector : 'zingchart',
  inputs : ['chart'], 
  template : `
   <div id='{{chart.id}}'></div>
  `
})
class ZingChart implements AfterView, OnDestroy {
  chart : Chart;
  constructor(private zone:NgZone) {
  }

  ngAfterViewInit() {
      this.zone.runOutsideAngular(() => {
          zingchart.render({
              id : this.chart['id'],
              data : this.chart['data'],
              width : this.chart['width'],
              height: this.chart['height']
          });
      });
  }
  ngOnDestroy() {
      zingchart.exec(this.chart['id'], 'destroy');
  }
}

//Root Component
@Component({
  selector: 'my-app',
  directives: [ZingChart]
  template: `
    <zingchart *ngFor="#chartObj of charts" [chart]='chartObj'></zingchart>
     <button type="button" class="btn btn-default" (click)="rerender()">re-render</button>
  `,
})
export class App {
  charts : Chart[];
  constructor() {
    this.name = 'Angular2'
    this.charts = [{
      id : 'chart-1',
      data : {
        type : 'line',
        series : [{
          values :[2,3,4,5,3,3,2]
        }],
      },
      height : 400,
      width : 600
    }]
  }

  rerender(){
    alert("please help me don't know  what to write here");
  }
}


bootstrap(App, [])
  .catch(err => console.error(err));
4

1 回答 1

5

我会使用@ViewChild装饰器从父组件引用图表组件:

@Component({
  selector: 'my-app',
  directives: [ZingChart]
  template: `
    <zingchart *ngFor="#chartObj of charts" [chart]='chartObj'></zingchart>
    <button type="button" class="btn btn-default" (click)="rerender()">re-render</button>
  `,
})
export class App {
  charts : Chart[];

  @ViewChild(ZingChart)
  chart: ZingChart;

  (...)
}

这样,您将能够调用图表组件本身的方法。一个渲染例如:

@Component({
  (...)
})
export class App {
  (...)
  rerender(){
    this.chart.render();
  }
}

看到这个 plunkr:https ://plnkr.co/edit/NggADnGRbw4TsYiIUsh3?p=preview

于 2016-05-19T09:26:37.417 回答