Ionic5 组件获取@ViewChild 不工作

Ionic5 component get @ViewChild not working

我正在尝试根据这些示例将绘图实现到离子组件中: https://enappd.com/blog/charts-in-ionic-4-apps-and-pwa-part-1/52/

我只是将内容复制并粘贴到一个组件中,但是当我 运行 组件时 @ViewChild 将找不到。我尝试使用 ionic native @ViewChild 选项和 document.getElementByID 但两者都不会 return 绘图元素。 this.barChart。将未定义并使 createBarChart 函数崩溃。

我觉得因为它是一个组件,所以 document.getElementByID 搜索父文档树而不是组件文档。

HTML:

<ion-content>
  <ion-card class="welcome-card">
    <ion-card-header>
      <ion-card-subtitle>Number of Viewers per season for</ion-card-subtitle>
      <ion-card-title>Game of Thrones</ion-card-title>
    </ion-card-header>
    <ion-card-content>
      <canvas #barChart></canvas>
    </ion-card-content>
  </ion-card>
</ion-content>

TS

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { Chart } from 'chart.js';

@Component({
  selector: 'app-plot',
  templateUrl: './plot.component.html',
  styleUrls: ['./plot.component.scss'],
})
export class PlotComponent implements OnInit {

  @ViewChild('barChart') barChart: ElementRef;

  bars: any;
  colorArray: any;

  constructor() { }

  ngOnInit() {
    this.createBarChart();
  }

  createBarChart() {
    this.bars = new Chart(this.barChart.nativeElement, {
      type: 'bar',
      data: {
        labels: ['S1', 'S2', 'S3', 'S4', 'S5', 'S6', 'S7', 'S8'],
        datasets: [{
          label: 'Viewers in millions',
          data: [2.5, 3.8, 5, 6.9, 6.9, 7.5, 10, 17],
          backgroundColor: 'rgb(38, 194, 129)', // array should have same number of elements as number of dataset
          borderColor: 'rgb(38, 194, 129)', // array should have same number of elements as number of dataset
          borderWidth: 1
        }]
      },
      options: {
        scales: {
          yAxes: [{
            ticks: {
              beginAtZero: true
            }
          }]
        }
      }
    });
  }
}

正如@fridoo 提到的,您正在尝试初始化 ngOnInit 挂钩中的 dom 元素,而模板代码尚未初始化。

特别是对于 HTMLCanvasElement,最好使用 Ionic 的 IonViewDidEnter 挂钩,因为这样您的 Canvas 元素和其他元素(例如 ion-header)将完全初始化,您将能够可靠地引用该元素的还有它的偏移量。

你可以这样看:

import { Component, ViewChild, ElementRef } from '@angular/core';
import { AlertController } from '@ionic/angular';
@Component({
  selector: 'my-page',
  templateUrl: './my-page.component.html',
  styleUrls: ['./my-page.component.css']
})
export class MyPageComponent {

  @ViewChild('barChart') barChart: ElementRef;

  constructor() {}

  ngOnInit() {
    console.log(this.barChart)
    if (this.barChart) {
      console.log(this.barChart.nativeElement.getBoundingClientRect())
    }
  };

  ngAfterViewInit() {
    console.log(this.barChart)
    if (this.barChart) {
      console.log(this.barChart.nativeElement.getBoundingClientRect())
    }
  };

  ionViewDidEnter() {
    console.log(this.barChart)
    if (this.barChart) {
      console.log(this.barChart.nativeElement.getBoundingClientRect())
    }
  };
  
}