在父类中保留ViewChild的引用

时间:2018-04-19 11:17:42

标签: angular viewchild

我想通过@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

1 个答案:

答案 0 :(得分:0)

只有在视图为init后才能访问@ViewChild个查询。您需要将代码移至ngAfterViewInit

您也可能遇到装饰器继承的一些问题。有关详细信息,请查看此github issue