[英]getElementById on element from parent component returns null, when called in ngAfterViewInit() of child component
I am trying to display dynamic number of charts by loading child components from parent component.我试图通过从父组件加载子组件来显示动态数量的图表。
I have created an array barChart
in Parent where I have the ids ['Canvas0', 'Canvas1'...]
.我在 Parent 中创建了一个数组
barChart
,其中的 ids ['Canvas0', 'Canvas1'...]
。 But I am getting following error,但我收到以下错误,
TypeError: Cannot read property 'getContext' of null in
var ctx = canvas.getContext("2d");
类型错误:无法在
var ctx = canvas.getContext("2d");
读取 null 的属性“getContext”var ctx = canvas.getContext("2d");
of Child Component.子组件。
Parent HTML:父 HTML:
<div *ngFor="let chart of barChart; let i = index">
<app-bar-chart [chart]="chart" style="border: 2px solid;" ></app-bar-chart>
</div>
Child 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
},
}
});
}
}
Child HTML:子 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装饰器从组件模板中查询元素
BarChartComponet条形图组件
@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
},
}
});
}
template模板
<div style="width:400px; height:100%;">
<canvas #chartElm ></canvas>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.