【发布时间】:2021-06-15 02:58:15
【问题描述】:
我正在尝试通过我目前正在从事的项目使用 Angular 学习 ng2-charts。
所以基本上,我首先尝试了一个新的 Angular 项目,安装了 ng2-charts
npm i ng2-charts chart.js
我试图通过将数据传递给子组件来实现它。 现在我想知道为什么我的图表(子组件)没有显示任何内容。
代码是这样的。
图表组件 // sample-chart.component.ts
import { Component, Input, OnInit } from "@angular/core";
@Component({
selector: "app-sample-chart",
templateUrl: "./sample-chart.component.html",
styleUrls: ["./sample-chart.component.css"],
})
export class SampleChartComponent implements OnInit {
@Input() barChartData;
@Input() barChartLabels;
@Input() barChartOptions;
@Input() barChartPlugins;
@Input() barChartLegend;
@Input() barChartType;
constructor() {}
ngOnInit() {
console.log(this.barChartData, "data");
}
}
图表组件 // sample-chart.component.html
<canvas
baseChart
[datasets]="barChartData"
[labels]="barChartLabels"
[options]="barChartOptions"
[plugins]="barChartPlugins"
[legend]="barChartLegend"
[chartType]="barChartType"
>
</canvas>
应用组件 // .ts 文件
import { Component } from "@angular/core";
import { ChartOptions, ChartType, ChartDataSets } from "chart.js";
import { Label } from "ng2-charts";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"],
})
export class AppComponent {
title = "app";
public barChartOptions: ChartOptions = {
responsive: true,
// We use these empty structures as placeholders for dynamic theming.
scales: { xAxes: [{}], yAxes: [{}] },
plugins: {
datalabels: {
anchor: "end",
align: "end",
},
},
};
public barChartLabels: Label[] = [
"2006",
"2007",
"2008",
"2009",
"2010",
"2011",
"2012",
];
public barChartType: ChartType = "bar";
public barChartLegend = true;
public barChartData: ChartDataSets[] = [
{ data: [65, 59, 80, 81, 56, 55, 40], label: "Series A" },
{ data: [28, 48, 40, 19, 86, 27, 90], label: "Series B" },
];
}
应用组件 // .html 文件
<div style="text-align: center">
<h1>Welcome to {{ title }}!</h1>
<div style="display: block">
<app-sample-chart
[barChartData]="barChartData"
[barChartLabels]="barChartLabels"
[barChartOptions]="barChartOptions"
[barChartPlugins]="barChartPlugins"
[barChartLegend]="barChartLegend"
[barChartType]="barChartType"
>
</app-sample-chart>
</div>
<!-- <router-outlet></router-outlet> -->
</div>
如果相关,这里是使用的版本。
使用的图表和 ng2-charts 版本
"@angular/core": "^6.0.3",
"chart.js": "^2.9.4",
"ng2-charts": "^2.4.2",
我做错了吗?有什么建议吗?
【问题讨论】:
-
在控制台显示任何错误?
-
如果没有,请检查 ChartsModule 是否已导入 app.module.ts?
-
@AmanGojariya,是的,没有显示错误。我正在获取以
@Input()传递的数据。 -
请将显示块 div 移除到 app.component 并添加到图表 component.html
-
我已经发布了答案。如果它对你有用,请标记是正确的
标签: angular chart.js ng2-charts