簡體   English   中英

在子組件的 ngAfterViewInit() 中調用時,來自父組件的元素上的 getElementById 返回 null

[英]getElementById on element from parent component returns null, when called in ngAfterViewInit() of child component

我試圖通過從父組件加載子組件來顯示動態數量的圖表。

我在 Parent 中創建了一個數組barChart ,其中的 ids ['Canvas0', 'Canvas1'...] 但我收到以下錯誤,

類型錯誤:無法在var ctx = canvas.getContext("2d");讀取 null 的屬性“getContext” var ctx = 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
        },
      }
    });
  }
}

子 HTML:

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

您可以使用@ViewChild裝飾器從組件模板中查詢元素

條形圖組件

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

演示🚀🚀

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM