我正在尝试基于这些示例将一个图实现为一个离子组件:https://enappd.com/blog/charts-in-ionic-4-apps-and-pwa-part-1/52/
我只是简单地将内容复制并粘贴到一个组件中,但是当我运行该组件时,将找不到@ViewChild。我使用ionic原生@ViewChild选项和document.getElementByID进行了尝试,但两者都不会返回plot元素。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
}
}]
}
}
});
}
}发布于 2020-08-24 00:01:45
正如@fridoo提到的,你正试图在ngOnInit钩子中初始化一个dom元素,而模板代码还没有初始化。
具体地说,对于HTMLCanvasElement,最好使用Ionic的IonViewDidEnter钩子,因为这样您的画布元素和其他元素(如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())
}
};
}https://stackoverflow.com/questions/63547935
复制相似问题