[英]Ionic5 component get @ViewChild not working
我正在嘗試根據這些示例將繪圖實現到離子組件中: https : //enappd.com/blog/charts-in-ionic-4-apps-and-pwa-part-1/52/
我只是將內容復制並粘貼到組件中,但是當我運行該組件時,將找不到@ViewChild
。 我嘗試使用離子本機@ViewChild
選項和document.getElementByID
但兩者都不會返回繪圖元素。 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())
}
};
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.