1

我想通过在我的父类中声明的@ViewChild 访问我的子组件中的图表。我不想为每个子类重新声明一个新变量。

父类:

import { Component, ViewChild} from '@angular/core';
import { BaseChartDirective } from 'ng2-charts';
import { LabelOptions } from '../labelOptions';

@Component({
  selector: 'app-graph',
  styleUrls: ['./graph.component.css']
})
export class GraphComponent {

  @ViewChild(BaseChartDirective) public chart: BaseChartDirective;
  //[.....some properties of a Graph.....]

  public setChart(data: any[], labels: string[]){
      this.chart.labels = labels;
      this.chart.datasets = data;
      this.update();
  }

}

儿童班:

import { Component, OnInit } from '@angular/core';
import { GraphComponent } from '../../../shared/graph/graph.component';

@Component({
  selector: 'app-pie-graph',
  templateUrl: './pie-graph.component.html',
  styleUrls: ['./pie-graph.component.css']
})
export class PieGraphComponent extends GraphComponent implements OnInit {

  constructor(){
    super();
    this.setType("pie");
  }

  public chartHovered(e:any): void {
    console.log(e);
  }

  ngOnInit(){
    this.setType("pie");
    console.log(this.chart);
    this.setChart([234, 234, 234], ["a", "b", "c"]);
    //console.log(this.chart);
  }
}

当我尝试访问父类的方法时出现问题,它使我无法定义,在我的情况下,问题在于setChart

4

1 回答 1

0

@ViewChild只有在视图初始化后才能访问查询。您需要将代码移动到ngAfterViewInit.

你也可能会遇到装饰器继承的一些问题。查看这个github 问题以获取更多信息。

于 2018-04-19T11:23:51.130 回答