Ionic/Chart.js - 无法读取未定义的属性“nativeElement”

问题描述 投票:0回答:4

我有一个简单的项目,显示一个 Ionic 段,其中有一个 Chart.js 条形图。我显示图表本身没有问题,但尝试将图表 HTML 放入 Ionic 段中会出现以下错误:

ERROR TypeError: Cannot read property 'nativeElement' of undefined
    at HomePage.webpackJsonp.203.HomePage.ionViewDidLoad (home.ts:19)

如果我只是移动

<canvas #barcanvas></canvas>
并将其放置在 .html 文档中的几乎任何其他位置,图表就会很好地显示,但不会显示在 Ionic 段元素内。

home.html

<ion-header>
  <ion-navbar>
    <ion-title>
      Ionic Blank
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <div padding>
    <ion-segment [(ngModel)]="pet">
      <ion-segment-button value="kittens">
        Kittens
      </ion-segment-button>
      <ion-segment-button value="puppies">
        Puppies
      </ion-segment-button>
    </ion-segment>
  </div>

  <div [ngSwitch]="pet">
    <ion-list *ngSwitchCase="'puppies'">
      puppies...
      <canvas #barcanvas></canvas>
    </ion-list>

    <ion-list *ngSwitchCase="'kittens'">
      kittens...
    </ion-list>
  </div>
</ion-content>

home.ts

import { Component, ViewChild } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Chart } from 'chart.js';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  @ViewChild('barcanvas') barcanvas;
  barChart: any;

  constructor(public navCtrl: NavController) {

  }

  ionViewDidLoad() {

    this.barChart = new Chart(this.barcanvas.nativeElement, {

      type: 'bar',
      data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
          label: '# of Votes',
          data: [12, 19, 3, 5, 2, 3],
          backgroundColor: [
            'rgba(255, 99, 132, 0.2)',
            'rgba(54, 162, 235, 0.2)',
            'rgba(255, 206, 86, 0.2)',
            'rgba(75, 192, 192, 0.2)',
            'rgba(153, 102, 255, 0.2)',
            'rgba(255, 159, 64, 0.2)'
          ],
          borderColor: [
            'rgba(255,99,132,1)',
            'rgba(54, 162, 235, 1)',
            'rgba(255, 206, 86, 1)',
            'rgba(75, 192, 192, 1)',
            'rgba(153, 102, 255, 1)',
            'rgba(255, 159, 64, 1)'
          ],
          borderWidth: 1
        }]
      }

    });

  }
}
angular ionic3 chart.js
4个回答
4
投票

如果您使用 Angular >=8,现在您必须将第二个参数传递给 Viewchild 以获取选项并设置 static: true

@ViewChild('barcanvas', {static: true}) barcanvas;

0
投票

在 home.ts 中,您正在 ionViewDidLoad 中加载栏,因此如果您想以这种方式放置它, 你不能把它放在段中,因为段将无法读取ionViewDidLoad内部数据,因为执行ionViewDidLoad函数后段也在加载,否则如果你想把它放在段中, 您应该从 ionViewDidLoad() 中取出数据并将它们放入其他函数中,因此您可以将函数直接放入段中,从而该函数可以被段读取。


0
投票

ionViewDidLoad()不要使用这个。只需使用这个:ionViewDidEnter()


0
投票

如果有人遇到此问题,另一个可能的答案: 在模板中,如果图表画布处于某个条件(if、ng-template、switch 等)内,则可能找不到 nativeElement。您可以设置一个计时器,给浏览器时间来解决它。例如在 .ts 文件中:

setTimeout(() => {
  this.ionViewDidLoad();
}, 50);

在本期中,画布位于开关盒内。

© www.soinside.com 2019 - 2024. All rights reserved.