angular里如何使用echarts

125 阅读1分钟

安装

我使用的是angular15,所以ngx-echarts使用的15.x.x的版本,这里需要注意对应版本正确

  1. npm install echarts -S
  2. npm install ngx-echarts@15.0.3 -S

使用方式

官方上有三种加载的方式,具体可见www.npmjs.com/package/ngx…

  1. ngModule,
  2. 主包使用NgxEchartsModule.forRoot({ echarts }),,
  3. 独立组件中使用providers: [ { provide: NGX_ECHARTS_CONFIG, useFactory: () => ({ echarts: () => import('echarts') }) }, ]

具体使用

我使用的是第三种,具体代码

  • html

<div echarts [options]="chartOption" class="demo-chart"></div>

  • ts
    import { EChartsOption } from 'echarts';
    import { NgxEchartsModule, NGX_ECHARTS_CONFIG } from 'ngx-echarts';
    @Component({
      selector: 'app-parent',
      templateUrl: './parent.component.html',
      styleUrls: ['./parent.component.scss'],
      standalone: true,
      imports: [
        NgxEchartsModule
      ],
      providers: [
        {
          provide: NGX_ECHARTS_CONFIG,
          useFactory: () => ({ echarts: () => import('echarts') })
        },
      ]
    })
    export class ParentComponent implements OnInit {
      chartOption: EChartsOption = {
        tooltip: {
          trigger: 'item'
        },
        legend: {
          top: '5%',
          left: 'center'
        },
        series: [
          {
            name: '比例',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '40',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: [
              { value: 111, name: '张三' },
              { value: 222, name: '李四' },
              { value: 333, name: '王五' },
            ]
          }
        ]
      }
    }