在angular中使用echart,必须安装echart依赖和ngx-echart依赖
在app.module.ts中导入ngx-echarts依赖之后,在@NgModule中导入 echart依赖
安装步骤
npm install echarts -S
npm install ngx-echarts -S
app.module.ts 代码如下:
import {NgxEchartsModule } from 'ngx-echarts';@NgModule({imports: [NgxEchartsModule.forRoot({/*** This will import all modules from echarts.* If you only need custom modules,* please refer to [Custom Build] section.*/echarts: () => import('echarts'), // or import('./path-to-my-custom-echarts')}),],})
在component中使用echarts,代码:
<div echarts [options]="options" class="demo-chart" (chartInit)="onChartInit($event)"></div>
component.ts:
import {EChartOption } from 'echarts';export class TeachnumberComponent implements OnInit {onChartInit(ec) {this.echartsIntance = ec;//获取到echart对象},methods(data1) {//数据切换之后调用此函数来渲染echartthis.options = {backgroundColor: '#31313D',title: {show: false},tooltip: {trigger: 'axis',axisPointer: {type: 'shadow'}},legend: {show: false},grid: {containLabel: true,show: false},xAxis: {type: 'category',boundaryGap: [0, 0.01],show: true,data: data1.yAxisData,},yAxis: {type: 'value',axisLine: {show: false },axisTick: {show: false},axisLabel: {show: true,}},textStyle: {fontSize: 18,color: '#fff'},series: [{type: 'bar',data: data1.seriesData,itemStyle: {normal: {label: {formatter: function (c) {return (c.data).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");},show: true,position: "top",textStyle: {fontWeight: "normal",fontSize: "12",color: "#fff"}},color: function (params) {var colorList = ['#FADD6F', '#8F6CD0', '#FE914C', '#F899C5', '#3CC8A1', '#44B9FF'].reverse()return colorList[params.dataIndex]}},},},]};this.echartsIntance.setOption(this.options); //手动重新渲染echart}}
动态更新数据核心内容:通过onChartInit()函数,在初始化时获取到echart对象,然后使用echartsIntance.setOption()方法重新渲染echart。