繁体   English   中英

在子组件的 ngAfterViewInit() 中调用时,来自父组件的元素上的 getElementById 返回 null

[英]getElementById on element from parent component returns null, when called in ngAfterViewInit() of child component

我试图通过从父组件加载子组件来显示动态数量的图表。

我在 Parent 中创建了一个数组barChart ,其中的 ids ['Canvas0', 'Canvas1'...] 但我收到以下错误,

类型错误:无法在var ctx = canvas.getContext("2d");读取 null 的属性“getContext” var ctx = canvas.getContext("2d"); 子组件。

父 HTML:

<div *ngFor="let chart of barChart; let i = index">
    <app-bar-chart [chart]="chart"  style="border: 2px solid;" ></app-bar-chart>
</div>

儿童打字稿:

export class BarChartComponent implements OnInit {
  @Input() chart: any;

  constructor() { }

  ngOnInit() {
    console.log(this.chart)
  }

  ngAfterViewInit() {
    //setTimeout(()=>{
    //  this.addchart(this.chart);
    //}, 3000);
    this.addchart(this.chart); 
  }

  public addchart(chartid){
    console.log(chartid);
    var canvas = <HTMLCanvasElement> document.getElementById(chartid);
    console.log(document.getElementById(chartid));
    var ctx = canvas.getContext("2d");
    var mychart = new Chart(ctx, {
      type: 'bar',
      data: {
          labels: ['Red', 'Blue'],
          datasets: [{
              label: '# of Votes',
              data: [12, 19],
              backgroundColor: 'lightgreen',
              borderColor: 'blue',
              borderWidth: 1
          }]
      },
      options: {
          legend: {
            display: false
        },
      }
    });
  }
}

子 HTML:

<div *ngIf="chart">
  <canvas id="{{chart}}" width="400" height="400">{{chart}}</canvas>
</div>

您可以使用@ViewChild装饰器从组件模板中查询元素

条形图组件

  @ViewChild('chartElm', { static: true }) public chartElm: ElementRef;

  ngAfterViewInit() {
    this.addchart(); 
  }

  public addchart(){
    var canvas = <HTMLCanvasElement> this.chartElm.nativeElement; // 👈

    var ctx = canvas.getContext("2d");
    var mychart = new Chart(ctx, {
      type: 'bar',
      data: {
          labels: ['Red', 'Blue'],
          datasets: [{
              label: '# of Votes',
              data: [12, 19],
              backgroundColor: 'lightgreen',
              borderColor: 'blue',
              borderWidth: 1
          }]
      },
      options: {
          legend: {
            display: false
        },
      }
    });
  }

模板

<div style="width:400px; height:100%;"> 
  <canvas #chartElm ></canvas>
</div>

演示🚀🚀

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM