2017-07-30 103 views
2

我想弄清楚为什么角4 ChartJS组件不呈现。为什么我的Angular 4 ChartJS组件不能渲染?

我已经安装了使用纱线的包装,它存在并正确导入。我可以在chrome控制台中看到Chart对象,但画布元素保持空白。

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); 
    } 
} 

回答

1

您需要确保含元件具有`块”的显示类型canvas元件。如前面的线程指出,它可以被包装在一个div,或angular4,只需将设置:主机CSS元素:

:host { 
    display: block 
} 
0

您需要包围内部div

template: '<div><canvas #aChart></canvas></div>', 
+1

这工作 - 可以请你修改你的答案来解释为什么我会将其标记为已接受。 –

+0

这似乎只是设置:在CSS文件中的主机{显示:块}也适用 –