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

Javascript 在子组件的ngAfterViewInit()中调用时,来自父组件的元素上的getElementById返回null,javascript,angular,typescript,chart.js,Javascript,Angular,Typescript,Chart.js,我试图通过从父组件加载子组件来显示图表的动态数量 我已经在父级中创建了一个数组条形图,其中我有ID['Canvas0','Canvas1'…]。但我有以下错误 TypeError:无法在var ctx中读取null的属性“getContext”= canvas.getContext(“2d”) 父HTML: <div *ngFor="let chart of barChart; let i = index"> <app-bar-chart [chart]="chart"

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

我已经在父级中创建了一个数组
条形图
,其中我有ID
['Canvas0','Canvas1'…]
。但我有以下错误

TypeError:无法在
var ctx中读取null的属性“getContext”=
canvas.getContext(“2d”)

父HTML:

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

子类型脚本:

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
        },
      }
    });
  }
}
导出类BarChartComponent实现OnInit{
@Input()图表:任意;
构造函数(){}
恩戈尼尼特(){
console.log(this.chart)
}
ngAfterViewInit(){
//设置超时(()=>{
//this.addchart(this.chart);
//}, 3000);
this.addchart(this.chart);
}
公共addchart(chartid){
console.log(chartid);
var canvas=document.getElementById(chartid);
log(document.getElementById(chartid));
var ctx=canvas.getContext(“2d”);
var mychart=新图表(ctx{
类型:'bar',
数据:{
标签:[“红色”、“蓝色”],
数据集:[{
标签:“#投票数”,
数据:[12,19],
背景颜色:“浅绿色”,
边框颜色:“蓝色”,
边框宽度:1
}]
},
选项:{
图例:{
显示:假
},
}
});
}
}
子HTML:

<div *ngIf="chart">
  <canvas id="{{chart}}" width="400" height="400">{{chart}}</canvas>
</div>

{{chart}}
您可以使用@ViewChild装饰器从组件模板查询元素

条形复合物

@ViewChild('chartElm',{static:true})公共chartElm:ElementRef;
ngAfterViewInit(){
这个.addchart();
}
公共addchart(){

var canvas=this.chartElm.nativeElement;//错误已消失,但图表的宽度和高度为Nan,因此不是displayed@SwapnilGhosh检查这个演示我刚刚设置了一个组件样式,比如宽度和高度