gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 16:39:28 25 4
gpt4 key购买 nike

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

我创建了一个数组 barChart在我有 ID ['Canvas0', 'Canvas1'...] 的父级中.但我收到以下错误,

TypeError: Cannot read property 'getContext' of null in var ctx =
canvas.getContext("2d");
of Child Component.



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

子 typescript :
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>

最佳答案

you can use @ViewChild decorator to query an element from component template



条形图组件

  @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>

demo 🚀🚀

关于javascript - 在子组件的 ngAfterViewInit() 中调用时,父组件的元素上的 getElementById 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59501298/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com