【问题标题】:Keep reference of ViewChild in parent class在父类中保留 ViewChild 的引用
【发布时间】:2018-04-19 11:17:41
【问题描述】:

我想通过在我的父类中声明的@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

【问题讨论】:

    标签: angular viewchild


    【解决方案1】:

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

    你也可能会遇到装饰器继承的一些问题。查看此github issue 了解更多信息。

    【讨论】:

    • 非常感谢。我应该移动代码的哪些部分?
    • 只有在视图初始化后才能访问this.chart (ngAfterViewInit)。
    • export class PieGraphComponent extends GraphComponent implements OnInit, AfterViewInit { ngAfterViewInit(){ console.log(this.chart); //this.setChart([234, 234, 234], ["a", "b", "c"]); } this.chart 没问题,但是 setChart 有问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-29
    • 1970-01-01
    • 1970-01-01
    • 2020-11-25
    • 2015-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多