为什么我的Angular 4 ChartJS组件不能渲染?

Jac*_*phy 6 chart.js angular

我试图弄清楚为什么角度4 ChartJS组件没有渲染.

我已经使用纱线安装了包,它存在并正确导入.我可以在chrome控制台中看到Chart对象,但canvas元素仍然是空白的.

import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import Chart from 'chart.js';

@Component({
  selector: 'app-root',
  template: '<canvas #aChart></canvas>',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {
  @ViewChild('aChart') htmlChart: ElementRef;
  public data = {
    labels: [
      'Value A',
      'Value B'
    ],
    datasets: [
      {
        'data': [101342, 55342],   // Example data
        'backgroundColor': [
          '#1fc8f8',
          '#76a346'
        ]
      }]
  };

  constructor(public myElement: ElementRef) {}

  ngOnInit() {
    const ctx: CanvasRenderingContext2D = this.htmlChart.nativeElement.getContext('2d');
    const newChart: Chart = new Chart(ctx, {
      'type': 'doughnut',
      'data': this.data,
      'options': {
        'cutoutPercentage': 50,
        'animation': {
          'animateScale': true,
          'animateRotate': false
        }
      }
    });
    console.log('chart', newChart);
  }
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*kij 9

你需要在canvas里面包含元素div

template: '<div><canvas #aChart></canvas></div>',
Run Code Online (Sandbox Code Playgroud)


Jac*_*phy 2

您需要确保包含元素的显示类型为“块”。正如前面的线程中所指出的,它可以包装在 div 中,也可以包装在 angular4 中,只需将 :host css 元素设置为:

:host { 
  display: block 
}
Run Code Online (Sandbox Code Playgroud)