使用@ViewChildren处理Highcharts

时间:2017-06-09 12:13:04

标签: angular highcharts

如何在Angular 2中使用Highcharts(基本折线图):https://angular2highcomponents.azurewebsites.net/LineCharts/BasicLine

我想知道如何动态实现它,而不知道我将绘制多少图表。这是我尝试过的(并且失败了):

在我的component.ts中:

@ViewChildren('chart') components: QueryList<any>;
Highcharts.chart(this.components.toArray()[0].nativeElement, this.lineConfig); //with a legit lineConfig, of course

在我的component.html中:

<div *ngFor="let widget of widgets" class="col-xs-12 col-sm-6 placeholder2">
        <div #chart style="width:100%; height:300px;"></div>
      </div>

我收到此错误:

  

TypeError:无法读取未定义

的属性“nativeElement”

我收到此错误,因为组件数组未启动但使用viewChild,这不是问题(正如您在示例中所见)

提前致谢。

1 个答案:

答案 0 :(得分:0)

你可以尝试几件事,我会将它们全部分组:

import { Component, OnInit, AfterViewInit, AfterViewChecked } from '@angular/core';

export class YourClass, implements OnInit, AfterViewInit, AfterViewChecked {
    ngOnInit() {
        Highcharts.chart(this.components.toArray()[0].nativeElement, this.lineConfig); //with a legit lineConfig, of course
    }
    ngAfterViewInit() {
        Highcharts.chart(this.components.toArray()[0].nativeElement, this.lineConfig); //with a legit lineConfig, of course
    }
    ngAfterViewChecked() {
        Highcharts.chart(this.components.toArray()[0].nativeElement, this.lineConfig); //with a legit lineConfig, of course
    }
}

尝试使用AfterViewChecked first, it should work.