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 に答える