Code Monkey home page Code Monkey logo

ngx-echarts's Introduction

Logo

NGX-ECHARTS

Angular directive for Apache ECharts

Online Demo | Starter

Table of contents

Getting Started

ngx-echarts is an Angular (ver >= 2.x) directive for ECharts (ver >= 3.x).

Latest version @npm:

  • v18.0.0 for Angular 18
  • v17.2.0 for Angular 17
  • v16.2.0 for Angular 16
  • v15.0.3 for Angular 15
  • v14.0.0 for Angular 14
  • v8.0.1 for Angular 13
  • v7.1.0 for Angular >= 11, < 13
  • v6.0.1 for Angular >= 10, < 11
  • v5.2.2 for Angular >= 6, < 10
  • v2.3.1 for Angular < 6 (Please refer to https://github.com/xieziyu/ngx-echarts/blob/v2.x/README.md)

A starter project on Github: https://github.com/xieziyu/ngx-echarts-starter

Latest Update

  • 2024.05.25: v18.0.0
    • Feat: Upgrade to angular 18

CHANGELOG.md

Installation

  • Since v5.0

    # if you use npm
    npm install echarts -S
    npm install ngx-echarts -S
    
    # or if you use yarn
    yarn add echarts
    yarn add ngx-echarts
  • If you need ECharts GL support, please install it first:

    npm install echarts-gl -S
    
    # or
    yarn add echarts-gl
  • Import other extensions such as themes or echarts-gl in your main.ts: ECharts Extensions

Upgrade from v4.x

  1. import echarts and provide it in NgxEchartsModule.forRoot({ echarts }).
  2. NgxEchartsCoreModule is removed.

Usage

Please refer to the demo page.

Standalone

import NgxEchartsDirective and provideEcharts. Or you can use provideEchartsCore to do treeshaking custom build.

import { NgxEchartsDirective, provideEcharts } from 'ngx-echarts';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule, NgxEchartsDirective],
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  providers: [
    provideEcharts(),
  ]
})
export class AppComponent {}

NgModule

import NgxEchartsModule:

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')
    }),
  ],
})
export class AppModule {}

The echarts library will be imported only when it gets called the first time thanks to the function that uses the native import.

You can also directly pass the echarts instead which will slow down initial rendering because it will load the whole echarts into your main bundle.

import * as echarts from 'echarts';
import { NgxEchartsModule } from 'ngx-echarts';

@NgModule({
  imports: [
    NgxEchartsModule.forRoot({ echarts }),
  ],
})
export class AppModule {}

Directive

use echarts directive in a div which has pre-defined height. (From v2.0, it has default height: 400px)

  • html:
<div echarts [options]="chartOption" class="demo-chart"></div>
  • css:
.demo-chart {
  height: 400px;
}
  • component:
import { EChartsOption } from 'echarts';

// ...

chartOption: EChartsOption = {
  xAxis: {
    type: 'category',
    data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
  },
  yAxis: {
    type: 'value',
  },
  series: [
    {
      data: [820, 932, 901, 934, 1290, 1330, 1320],
      type: 'line',
    },
  ],
};

API

Directive

echarts directive support following input properties:

Input Type Default Description
[options] object null The same as the options on the official demo site.
[merge] object null Used to update a part of the options, especially helpful when you need to update the chart data. In fact, the value of merge will be used in echartsInstance.setOption() with notMerge = false. Refer to ECharts documentation for details.
[loading] boolean false Used to toggle the echarts loading animation when your data is not ready.
[autoResize] boolean true If set to true, the chart will be automatically resized when the window's width is changed.
[initOpts] object null The value of [initOpts] will be used in echarts.init(). It may contain devicePixelRatio, renderer, width or height properties. Refer to ECharts documentation for details.
[theme] string null Used it to initialize echarts with theme. The theme file must also be imported in main.ts.
[loadingOpts] object null Input an object to customize the loading style. Refer to ECharts documentation for details.

By default, loadingOpts is:

{
  text: 'loading',
  color: '#c23531',
  textColor: '#000',
  maskColor: 'rgba(255, 255, 255, 0.8)',
  zlevel: 0
}

ECharts API

If you need to access parts of the ECharts API such as echarts.graphic, please import it from echarts. For example:

import { graphic } from 'echarts';

new graphic.LinearGradient(/* ... */);

ECharts Instance

echartsInstance is exposed (since v1.1.6) in the (chartInit) event, enabling you to directly call functions like: resize(), showLoading(), etc. For example:

  • html:
<div echarts class="demo-chart" [options]="chartOptions" (chartInit)="onChartInit($event)"></div>
  • component:
onChartInit(ec) {
  this.echartsInstance = ec;
}

resizeChart() {
  if (this.echartsInstance) {
    this.echartsInstance.resize();
  }
}

ECharts Extensions

Import echarts theme files or other extension files after you have imported echarts core. For example:

import * as echarts from 'echarts';

/** echarts extensions: */
import 'echarts-gl';
import 'echarts/theme/macarons.js';
import 'echarts/dist/extension/bmap.min.js';

Service

NgxEchartsService has been obsolete since v4.0

Events

As ECharts supports the 'click', 'dblclick', 'mousedown', 'mouseup', 'mouseover', 'mouseout', and 'globalout' mouse events, our ngx-echarts directive also supports the same mouse events but with an additional chart prefix. For example:

  • html:
<div echarts class="demo-chart" [options]="chartOptions" (chartClick)="onChartClick($event)"></div>
  • The '$event' is same with the 'params' that ECharts dispatches.

It supports following event outputs:

@Output Event
chartInit Emitted when the chart is initialized
chartClick echarts event: 'click'
chartDblClick echarts event: 'dblclick'
chartMouseDown echarts event: 'mousedown'
chartMouseMove echarts event: 'mousemove'
chartMouseUp echarts event: 'mouseup'
chartMouseOver echarts event: 'mouseover'
chartMouseOut echarts event: 'mouseout'
chartGlobalOut echarts event: 'globalout'
chartContextMenu echarts event: 'contextmenu'
chartHighlight echarts event: 'highlight'
chartDownplay echarts event: 'downplay'
chartSelectChanged echarts event: 'selectchanged'
chartLegendSelectChanged echarts event: 'legendselectchanged'
chartLegendSelected echarts event: 'legendselected'
chartLegendUnselected echarts event: 'legendunselected'
chartLegendLegendSelectAll echarts event: 'legendselectall'
chartLegendLegendInverseSelect echarts event: 'legendinverseselect'
chartLegendScroll echarts event: 'legendscroll'
chartDataZoom echarts event: 'datazoom'
chartDataRangeSelected echarts event: 'datarangeselected'
chartGraphRoam echarts event: 'graphroam'
chartGeoRoam echarts event: 'georoam'
chartTreeRoam echarts event: 'treeroam'
chartTimelineChanged echarts event: 'timelinechanged'
chartTimelinePlayChanged echarts event: 'timelineplaychanged'
chartRestore echarts event: 'restore'
chartDataViewChanged echarts event: 'dataviewchanged'
chartMagicTypeChanged echarts event: 'magictypechanged'
chartGeoSelectChanged echarts event: 'geoselectchanged'
chartGeoSelected echarts event: 'geoselected'
chartGeoUnselected echarts event: 'geounselected'
chartAxisAreaSelected echarts event: 'axisareaselected'
chartBrush echarts event: 'brush'
chartBrushEnd echarts event: 'brushend'
chartBrushSelected echarts event: 'brushselected'
chartGlobalCursorTaken echarts event: 'globalcursortaken'
chartRendered echarts event: 'rendered'
chartFinished echarts event: 'finished'

You can refer to the ECharts tutorial: Events and Actions in ECharts for more details of the event params. You can also refer to the demo page for a detailed example.

Custom Build

Treeshaking Custom Build

Since version 5.0.1 ECharts supports Treeshaking with NPM.

The app.modules.ts should look like this:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import { NgxEchartsDirective, provideEchartsCore } from 'ngx-echarts';

import { AppComponent } from './app.component';

// Import the echarts core module, which provides the necessary interfaces for using echarts.
import * as echarts from 'echarts/core';

// Import bar charts, all suffixed with Chart
import { BarChart } from 'echarts/charts';

// Import the tooltip, title, rectangular coordinate system, dataset and transform components
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent
} from 'echarts/components';

// Features like Universal Transition and Label Layout
import { LabelLayout, UniversalTransition } from 'echarts/features';

// Import the Canvas renderer
// Note that including the CanvasRenderer or SVGRenderer is a required step
import { CanvasRenderer } from 'echarts/renderers';

// Import the theme
import 'echarts/theme/macarons.js';

// Register the required components
echarts.use([
  BarChart,
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  LabelLayout,
  UniversalTransition,
  CanvasRenderer
]);

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    HttpClientModule,
    // import standalone directive:
    NgxEchartsDirective,
  ],
  providers: [{ 
    // Provide custom builded ECharts core:
    provideEchartsCore({ echarts })
  }],
  bootstrap: [AppComponent],
})
export class AppModule {}

Legacy Custom Build

Please refer to ECharts Documentation for more details.

If you want to produce a custom build of ECharts, prepare a file like custom-echarts.ts:

// custom-echarts.ts
export * from 'echarts/src/echarts';

import 'echarts/src/chart/line';
import 'echarts/src/chart/bar';
// component examples:
import 'echarts/src/component/tooltip';
import 'echarts/src/component/title';
import 'echarts/src/component/toolbox';

And then inject it in your NgxEchartsModule:

import { NgxEchartsModule } from 'ngx-echarts';
import * as echarts from './custom-echarts';

@NgModule({
  imports: [
    NgxEchartsModule.forRoot({
      echarts,
    }),
  ],
})
export class AppModule {}

And if you want to use the global echarts object, please import it from lib or src instead:

import * as echarts from 'echarts/lib/echarts';

If you need to import theme files, remember to change the 'echarts' path to 'echarts/lib/echarts', for example:

// ... part of echarts/theme/dark.js:
function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['exports', 'echarts/lib/echarts'], factory);
    } else if (typeof exports === 'object' && typeof exports.nodeName !== 'string') {
        // CommonJS
        factory(exports, require('echarts/lib/echarts'));
    } else {
        // Browser globals
        factory({}, root.echarts);
    }
}

Custom Locale

You can change the chart locale registering a built-in locale (located in node_modules/echarts/lib/i18n/) or a custom locale object. To register a locale, you will need to change the module that echart is being imported (usually app.module.ts).

import {NgxEchartsModule} from "ngx-echarts";
import * as echarts from 'echarts/core';
import langCZ from 'echarts/lib/i18n/langCZ';

echarts.registerLocale("CZ", langCZ)

@NgModule({
  imports: [NgxEchartsModule.forRoot({echarts})],
  declarations: [],
  providers: [],
  bootstrap: [AppComponent]
})

and in your HTML file use:

<div echarts [initOpts]="{ locale: 'CZ' }" [options]="options" class="demo-chart"></div>

Demo

You can clone this repo to your working copy and then launch the demo page in your local machine:

npm install
npm run demo

# or
yarn install
yarn demo

The demo page server is listening on: http://localhost:4202

ngx-echarts's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ngx-echarts's Issues

Resize

Hi,
how to resize chart?
thanks

issue with rollup

when doing a rollup, it gives me.

'AngularEchartsModule' is not exported by node_modules/ngx-echarts/bundles/ngx-echarts.umd.js

my rollup.config.js is

import angular from 'rollup-plugin-angular';
import typescript from 'rollup-plugin-typescript2';
import commonjs from 'rollup-plugin-commonjs';
import nodeResolve from 'rollup-plugin-node-resolve';
import sass from 'node-sass';
import CleanCSS from 'clean-css';
import {
  minify as minifyHtml
} from 'html-minifier';
import uglify from 'rollup-plugin-uglify';

const cssmin = new CleanCSS();
const htmlminOpts = {
  caseSensitive: true,
};

export default {
  entry: 'src/main.ts',
  format: 'iife',
  dest: 'dist/bundle.js',
  plugins: [
    commonjs({
      include: 'node_modules/rxjs/**',
    }),
    angular({
      preprocessors: {
        template: template => minifyHtml(template, {
          collapseWhitespace: true,
          removeComments: true
        }),
        styleUrls: scss => {
          const css = sass.renderSync({
            data: scss
          }).css;
          return cssmin.minify(css).styles;
        }
      }
    }),
    typescript(),
    nodeResolve({
      jsnext: true,
      main: true
    }),
    uglify({
      toplevel: true,
      compress: {
        dead_code: true,
        sequences: true,
        unused: true,
        if_return: true,
        drop_console: true,
        drop_debugger: true,
        passes: 2
      }
    })
  ]
}

和tabset组件一起使用时,echarts图表宽高异常的问题

我想在tabset组件中使用二次封装的折线图组件,但是经常报 Can't get dom width or height 警告,但是所有折线图还是会被渲染出来。当前的tab(页面加载时显示的tab)中的折线图宽高正常,但是切换到其余tab中的折线图,折线图宽度只有 100px,我设置的宽度均为 100%(为了自适应),不知道大佬有没有遇到过这个问题?有没有什么解决办法
我个人觉得可能是tabset动态插入模板的时候,app-total-line 组件无法获取到父容器的宽高导致的。

部分代码如下:

tabset

# app-tabset是一个tabset组件
# app-tab表示tab页
# app-total-line 是对echarts指令的二次封装的组件
<div class="line-tab">
    <app-tabset (onSelect)="onTabSelect($event)">
        <app-tab title="全部">
            <app-total-line></app-total-line>
        </app-tab>
        <app-tab title="一个月" [active]="true">
            <app-total-line></app-total-line>
        </app-tab>
        <app-tab title="24小时">
            <app-total-line></app-total-line>
        </app-tab>
    </app-tabset>
</div>

**tabset**组件模板

<nav class="tabset-style">
	<ul class="tabset-header" [ngClass]="customNavClass">
		<li role="presentation" *ngFor="let tab of tabs" [class.active]="tab.active"
			[class.disabled]="tab.disabled" (click)="changeActiveTab(tab)"
		>
			<span [appTabTransclude]="tab.headingTemplate">{{ tab.title }}</span>
		</li>
	</ul>
</nav>
<div class="tabs-container" [ngClass]="customTabsClass" [@.disabled]="!isAnimate">
	<div class="tabset-content">
		<ng-content></ng-content>
	</div>
</div>

app-total-line 组件

@Component({
    selector: 'app-total-line',
    template: `
        <div class="total-line">
            <app-line-echarts [option]="chartOption"></app-line-echarts>
        </div>
    `,
    styles: [`
        :host {
            width: 100%;
            height: 100%;
        }
    `]
})
export class TotalLineComponent {
    chartOption: ILineChart = {
        xAxisData: ['10-10', '10-11', '10-12', '10-13', '10-14', '10-15',
        '10-16', '10-17', '10-18', '10-19', '10-20', '10-21',
        '11-10', '11-11', '11-12', '11-13', '11-14', '11-15',
        '11-16', '11-17', '11-18', '11-19', '11-20', '11-21'],
        yAxisData1: [100, 123, 56, 12, 199,
            100, 123, 56, 12, 199,
            100, 123, 56, 12, 199,
            100, 123, 56, 12, 199,
            137, 7, 12, 342],
        yAxisData2: [137, 7, 12, 342, 341,
            137, 7, 12, 342, 341,
            137, 7, 12, 342, 341,
            137, 7, 12, 342, 341,
            143, 323, 112, 2]
    };
}

app-line-echarts 是对 echarts 指令的二次封装


@Component({
    selector: 'app-line-echarts',
    template: `
        <div class="line-echarts" echarts [options]="chartOption" (chartInit)="onChartInit($event)"
            [ngStyle]="{'width': chartWidth, 'height': chartHeight}"></div>
    `
})
export class LineChartComponent implements OnInit, OnChanges {
    chartInstance: any;
    private chartWidth: number | string = '100%';   // 宽度给的是100%,没有给固定值
    private chartHeight: number | string = '500px'; // 已经默认的给了一个高度500px
    @Input() option: ILineChart;
    @Input() showDataZoom = true;

    /**
     * 设置canvas的宽度
     * 支持数字和字符 或者 是 字符串带单位的形式
     */
    @Input()
    set width(val) {
        if (typeof val === 'number') {
           this.chartWidth = String(val) + 'px';
        } else if (typeof val === 'string' && (/^\d*$/g).test(val)) {
            this.chartWidth = val + 'px';
        } else {
            this.chartWidth = val;
        }
    }
    get width() {
        return this.chartWidth;
    }

    @Input()
    set height(val) {
        if (typeof val === 'number') {
           this.chartHeight = String(val) + 'px';
        } else if (typeof val === 'string' && (/^\d*$/g).test(val)) {
            this.chartHeight = val + 'px';
        } else {
            this.chartHeight = val;
        }
    }
    get height() {
        return this.chartHeight;
    }

    chartOption: any;

    constructor() {}
	
    onChartInit(ec) {
        this.chartInstance = ec;
    }
    ngOnInit(): void {
    }

    ngOnChanges(changes: SimpleChanges) {
 
        this._updateOption();
    }
	
	private _updateOption() {
	  // ...
	}
}	

手动改变下x,y轴的值,图表不跟着变化

setInterval(() => {
this.i = this.i + 1;
this.season.shift();
this.season.push(this.getSeason()[this.i]);
this.count.shift();
this.count.push(this.getCount()[this.i]);
this.increase.shift();
this.increase.push(this.getIncrease()[this.i]);
this.option.xAxis[0].data = this.season.slice();
this.option.series[0].data = this.count.slice();
this.option.series[1].data = this.increase.slice();
}, 5000);

单个实例里多个grid,非得点一下restore还原按钮才能 实现一起缩放

单个实例里多个grid,非得点一下restore还原按钮才能 实现一起缩放
let dataZoomArr = []; let xAxisArr=[]; let yAxisArr=[]; dataArr.forEach((value, index) => { dataZoomArr.push(index); xAxisArr.push({ gridIndex: index }); yAxisArr.push({ name: _this.sensorUnit, gridIndex: index, axisLine: { 'onZero': false }, }) }) console.log(dataZoomArr, '***'); this.updatetimeFreqChart = { dataZoom: [{ show: true, type: 'inside', xAxisIndex: dataZoomArr }, { show: true, type: 'slider', xAxisIndex: dataZoomArr }], xAxis: xAxisArr, yAxis: yAxisArr, grid: function () { let arr = []; let len = dataArr.length let _height = (520 - len * 40) / len; for (let i = 0; i < dataArr.length; i++) { let model = { height: _height, y: i * _height + 40 + 50 * i, } arr.push(model) } return arr; }(), series: function () { let arr = []; for (let i = 0; i < dataArr.length; i++) { let model = { name: '传感器名',//传感器名 type: 'line', xAxisIndex: i, yAxisIndex: i, data: dataArr[i], hoverAnimation: false, smooth: true, symbol: 'none', markLine: { silent: true, data: [], lineStyle: { normal: { color: '#c23531' } } }, lineStyle: { normal: { width: 0.5 } }, }; arr.push(model) } return arr; }() }

How to dynamic update the `xAxis.data`

@xieziyu
Thanks for your contribution.
I saw there is an attribute named dataset. It can dynamic update the series.
Then, I need it also can dynamic update xAxis.data, because my date is real-time who is come from socket data.
Could you help me?

绘制markLine出错

Angular Version:5.0

errorInfo:
image

code:
我在网上找了一份**地图数据 this.es.registerMap('CHINA', geoJson); 不知道是否和这个有关

markLine:[ data: [ [ { name: '北京' }, { name: '上海', value: 95 } ], // [{ name: '北京', x: 40, y: 100 }, { name: '包头', x: 140, y: 100 }], ], geoCoord: { '上海': [121.4648, 31.2891], '北京': [116.4551, 40.2539], }, ] ]

如果能给出这样的列子,那就更好了
image

Can't get a line chart to work...

What am I doing wrong here?

Ignore all the color variables

the chart shows an empty chart, no labels, no grids, no lines. Just a x and y axis line
like this
|_______

My pie chart works fine

<div echarts [options]="graphOptions" class="echart"></div>
            this.graphOptions = {
              backgroundColor: echarts.bg,
              color: [colors.danger, colors.primary, colors.info],
              xAxis: [
                {
                  type: 'time',
                  axisLine: {
                    lineStyle: {
                      color: echarts.axisLineColor,
                    },
                  },
                  axisLabel: {
                    textStyle: {
                      color: echarts.textColor,
                    },
                  },
                },
              ],
              yAxis: [
                {
                  type: 'value',
                  axisLine: {
                    lineStyle: {
                      color: echarts.axisLineColor,
                    },
                  },
                  splitLine: {
                    lineStyle: {
                      color: echarts.splitLineColor,
                    },
                  },
                  axisLabel: {
                    textStyle: {
                      color: echarts.textColor,
                    },
                  },
                },
              ],
              series: [
                {
                  name: 'Line 1',
                  type: 'line',
                  data: [
                    { name: "11/11/12", value: 1.1},
                    { name: "11/11/13", value: 2.1},
                    { name: "11/11/14", value: 2.1},
                    { name: "11/11/15", value: 1.1},
                    { name: "11/11/16", value: 1.1}
                  ]
                }
              ]
            };

Upgrade to latest echart version

Hi ziyu,

thanks for your efforts in this plugin! But we need some new features in echarts 3.7, for example, put sign at end of line chart, can you upgrade to the latest version?

请问angular-cli项目的环境中,npm引入后报如下 Warining该如何解决?

用angular-cli组装的工程中,
npm顺利安装了"echarts": "^3.7.1", 以及 "ngx-echarts": "^1.2.4",
也在.angular-cli.json中添加了引用:
"scripts": [
"../../node_modules/echarts/dist/echarts.min.js"
],
然后在moudle中也顺利引入了import { AngularEchartsModule } from 'ngx-echarts';

但是编译的时候报了两个警告:
WARNING in ./~/_@[email protected]@@angular/core/@angular/core.es5.js
5659:15-36 Critical dependency: the request of a dependency is an expression

WARNING in ./~/_@[email protected]@@angular/core/@angular/core.es5.js
5675:15-102 Critical dependency: the request of a dependency is an expression

运行时报错:
Uncaught Error: Unexpected value 'AngularEchartsModule' imported by the module 'ScalepageModule'. Please add a @NgModule annotation.

请教大家,这是什么原因?该如何解决,非常感谢。

基于ngx-echarts的再次封装的问题

没错大佬又是我。。。我想对常用的一些图形进行再一次封装,例如,对玫瑰图进行封装

const randomNumber = function(max: number = 400, min: number = 55): number {
    return Math.floor(Math.random() * (max - min) + min);
};

@Component({
    selector: 'app-rose-echarts',
    template: `
        <div class="rose-echarts" echarts [options]="chartOption" (chartInit)="onChartInit($event)"></div>
    `,
    styles: [`
        .rose-echarts {
            height: 600px;
        }
    `]
})
export class RoseChartComponent implements OnInit, OnChanges {
    chartInstance: any;

    @Input() title = ''; // 图的标题
    @Input() showLegend = false; // 是否显示图例
    @Input() roseType: RoseType = 'area'; // 默认面积模式
    @Input() name: string; // 图的名称
    @Input() isSortable = false; // 是否对取回的数据进行排序操作
    // @Input() chartData: any; // 图的数据
    chartData = [
        {name: '视频', value: randomNumber() },
        {name: '游戏', value: randomNumber() },
        {name: '音乐', value: randomNumber() },
        {name: '新闻', value: randomNumber() },
        {name: '阅读', value: randomNumber() },
        {name: '书刊', value: randomNumber() },
        {name: '体育', value: randomNumber() },
        {name: '漫画', value: randomNumber() },
        {name: '直播', value: randomNumber() },
        {name: '其它', value: randomNumber() }
    ]; // 数据


    chartOption: any = {
        title: {
            text: this.title
        },
        tooltip: {
             trigger: 'item'
        },
        legend: {
            show: this.showLegend
        },
        calculable : true,
        series: [
            {
                name: this.name,
                type: 'pie',
                radius: [20, 110],
                center: ['25%', 200],
                roseType: this.roseType,
                // itemStyle: []、
                data: this.isSortable ? this.chartData.sort((a, b) => a.value - b.value) : this.chartData
            }
        ]
    };

    constructor() {}

    ngOnInit(): void {
        console.log('11', this.chartOption);
    }
}

这里有一些输入属性,html为

<app-rose-echarts [isSortable]="true" [name]="'网站类型TOP10'"></app-rose-echarts>

但是我发现echarts在这些输入属性绑定之前就已经被渲染了,所以这些输入属性没有绑定到子组件中去。于是我使用了 OnChanges 钩子


export class RoseChartComponent implements OnInit, OnChanges {
    chartInstance: any;

    ngOnInit(): void {
        console.log('11', this.chartOption);
    }
    // ...
    ngOnChanges(changes: SimpleChanges) {
        console.log('changes', changes);
        if (changes.name) {
            this.chartOption.title.text = String(changes.name.currentValue);
        }
    }
}

这样可以实现绑定,但是这种对每个属性进行分别判断设置的方式,我觉得不太优雅,扩展性也不强,想请问一下,有没有别的方式对ngx-echarts进行再次的封装?

xAxis 不能赋值

你好,X轴的data好像不能赋值,我看dataset只是对series的值做操作,但是如果要做实时的曲线的,应该怎么实现的?谢谢了

可以添加地图图表吗?

请不知道你这个插件可以在angular上面做关于地图统计的图表吗? 比如说引入**地图,或者某个省份的地图。

echarts 指令不起作用

<div style="width: 100%;height:400px" echarts [options]="pieOption" (chartInit)="onSponsorPieChartInit($event)">
    loading..
</div>
<div style="width: 100%;height: 400px" echarts [options]="barOption" (chartInit)="onSponsorBarChartInit($event)">
    loading..
</div>

我有两个一模一样的模板,在另外的组件能生成图表在另外的组件则不起作用,没有任何提示信息,chartInit 事件绑定的函数也没有调用

我在一个cli的项目里面安装环境问题

我在一个cli的项目里面执行
npm install echarts --save
npm install ngx-echarts --save
之后就出现好几个类似这种的错误
ERROR in .//jquery/lib/node-jquery.js
Module not found: Error: Can't resolve 'xmlhttprequest' in 'F:\test\lite-version\node_modules\jquery\lib'
@ ./
/jquery/lib/node-jquery.js 8:28-53
@ ./src/lib.ts
@ ./src/main.ts
@ multi webpack-dev-server/client?http://localhost:4321 ./src/main.ts,
请教一下如何解决...

Charts constantly using CPU resources

As soon as a chart is initialized, even if it contains no data otherwise, it uses CPU resources even though it seems that if it's doing nothing, it shouldn't. How high the CPU usage is depends on the application but there always seems to be some.

This includes the ngx-echarts demo page, where I get 96% CPU usage from one Chrome process (as opposed to 0 everywhere on the Baidu echarts demo page).

Looking at the performance in Chrome's DevTools it seems a timer is triggered every 18ms or so that leads to various function calls.

Is this expected behavior? It doesn't seem so given the difference between the ngx-echarts and Baidu echarts demo pages, and it is causing problems on slower computers.

异步加载地图报错

我想异步加载'china.json'数据,然后再设置 geo: {map: 'china'}, 但是在异步请求之前echarts已经实例化了,出现报错信息: 'Map chinanot exists. You can download map file on'.

代码部分:
@Component({ selector: 'app-geographical-trend', template: <div echarts [options]="chartOption" class="demo-chart" (chartClick)="onClick($event)" *ngIf="!isLoading">`
})
class GeographicalTrendComponent implements OnInit {
isLoading = true;
chartInstance: any;
chinaGeo: string;
chartOption: any = undefined; // echarts 配置

constructor(@Inject('APP_CONFIG') private config: Object, private http: HttpClient) {
console.log(config); // { map: "../../assets/maps" }
this.chinaGeo = config['map'] + 'china.json'; // china.json 地图的地址
console.log(this.chinaGeo);
http.get(this.chinaGeo).subscribe((chinaMap) => { // 异步请求数据
this.isLoading = false;
echarts.registerMap('china', chinaMap); // 注册地图
console.log('init ', chinaMap);

this.chartOption = Object.assign({}, this.defaultOption, {
geo: {
map: 'china', // 声明map
// roam: true,
// ...
},
yAxis: {
data: this.categoryData.slice(0, 10).sort()
},
series : [
{
name: '选择器',
// type: 'scatter',
type: 'map',
mapType: 'china',
geoIndex: 0, // 同步数据
coordinateSystem: 'geo',
roam: true,
selectedMode: 'single',
itemStyle: {
normal: {
label: {
show: true,
color: '#fff' // 字体颜色
}
},
emphasis: {
label: {
show: true
}
}
},
data: this.provsName
},
{
id: 'bar',
zlevel: 2,
type: 'bar',
// ...
},
}
],
});
});
}
}
`
请问针对这种异步加载的情况有什么解决办法吗?

Can not get dataZoom to show up

I've tried all sorts of dataZoom properties but I can not get the section selector to show up at all.

My graph is a line graph and has a full days worth of data being displayed. When putting this inside the options object, it does not work.

"dataZoom": [
      {
        "show": true,
        "realtime": true,
        "start": 65,
        "end": 100
      }
    ],

I've tried multiple combinations of slider / inside types and nothing.

Does dataZoom work with a dataset graph? Has anyone else got dataZoom to work with a dataset?

在*ng-for中无法渲染图表

我定义了一个组件名叫app-pal-line-chart

<div echarts [options]="options" (chartInit)="onChartInit($event)" class="charts"></div>

在另一个组件中想要用ngFor动态渲染多个图表

<div class="pure-u-1-5" *ngFor="let pal of palValues">
    <app-pal-line-chart [palInfo]="pal" [subDateList]="dateList"></app-pal-line-chart>
</div>

但是在app-pal-line-chart组件里,ngOnChanges钩子里能够去到pal的值,但是无法取到ecInstance对象。如果不使用ngFor就可以取到。

我不可以循环去创建组件吗?

loading失效?我的ngx-echarts版本是1.2.4

<div echarts class="demo-chart" [options]="PV_second.options" [loading]="chartLoading" theme="dark"></div>

我在controller里面设置了
private chartLoading = true ;
但是没有loading显示出来。

另外我发现我这么写,竟然有loading

<div echarts class="demo-chart" [loading]="PV_second.options" [options]="PV_second.options" theme="dark"></div>

对,没错,就是loading的值等于[options]的值,这样子就有loading动画,神秘莫测啊

Theme is not getting updated

rough1
rough2
rough3

I am trying to add themes to my echarts but none is working and only default theme is set. I have attached 3 files. In first one, you can see I have included 'theme' property in my html file. In second file, you can see that I have imported that theme in my .angular-cli.json. In third file, you can see that my theme is there in node_modules>echarts>theme folder. Am I missing something?
I am following this link: " [https://xieziyu.github.io/ngx-echarts/#/usage/theme] ".

饼图出现缺某一块现象

点击饼图某一块时,重新设置options,出现startAngel of undefined并缺少某一块。但使用搜索或其他方式调用同样方法更新options却无此现象。

按GITHUB上示例,无法跑起来?

core.es5.js:1084 ERROR Error: Uncaught (in promise): Error: Template parse errors:
Can't bind to 'options' since it isn't a known property of 'div'. ("

][options]="echartOption" class="demo-chart">
): ng:///GoodsManageModule/SelfListsSearch.html@2:13 Error: Template parse errors: Can't bind to 'options' since it isn't a known property of 'div'.

请帮忙看下。
步骤:

1.npm install echarts --save
npm install ngx-echarts --save

  1. "../node_modules/echarts/dist/echarts.min.js"

import { NgxEchartsModule } from 'ngx-echarts';

@NgModule({
imports: [
...,
NgxEchartsModule
],
...
})
export class AppModule { }

  1. Simple example:

html:

....

这不是一个 Issue

试了无数,唯一个可以真正工作的 Echarts Ng2 封装,1024 个赞。

(chartsClick) 视图不更新

执行点击事件后 console.log 发现模型发生了变化,但是视图没有改变
让其他模型再次变化后(例如随意在另一个绑定了ngModel的input里输入"123"),视图才发生了变化

第一次运行会报错

你好,第一次运行报这个错:
error
只要到引入ngx-echarts的模块中将
odd
这一行剪切后再粘贴,保存一下就会自动运行,然后运行就成功了
success
很好奇为什么会有这种操作

ng build --prod 下出现的问题

我用的是angular-cli开发项目,用了ngx-echarts后,没有问题,页面也可以正常显示,当我重新ng serve的时候,会出现异常
ERROR in Error encountered resolving symbol values statically. Calling function 'ɵmakeDecorator', function calls are not supported. Co nsider replacing the function or lambda with a reference to an exported function, resolving symbol NgModule in /node_modules/[email protected]@ngx-echarts/node_modules/@angular/core/core.d.ts, resolving symbol Angular EchartsModule in /node_modules/[email protected]@ngx-echarts/index.d.ts, resolving symbol AngularEchartsModule in /node_modules/[email protected]@ngx-echarts/index.d. ts
再次complie又成功了,所以就没放在心上。

但当我用ng build --prod 打包项目的时候就会抛出同样的错误:
ERROR in Error encountered resolving symbol values statically. Calling function 'ɵmakeDecorator', function calls are not supported. Consider replacing the function or lambda with a reference to an exported function, resolving symbol Injectable in E:master/project/node_modules/ngx-echarts/node_modules/@angular/core/core.d.ts, resolving symbol ɵf in E:/master/project/node_modules/ngx-echarts/node_modules/@angular/core/core.d.ts, resolving symbol ɵf in E:/master/project/node_modules/ngx-echarts/node_modules/@angular/core/core.d.ts

ERROR in ./src/main.ts
Module not found: Error: Can't resolve './$$_gendir/app/app.module.ngfactory' in 'E:\master\project\s
rc'
@ ./src/main.ts 5:0-74
@ multi ./src/main.ts`

Echart is not defined

Hello,

I have the following error when I try to display a pie chart :

PieChartComponent.html:1 ERROR ReferenceError: echarts is not defined 
at angular-echarts.directive.js:30
at ZoneDelegate.invoke (zone.js:392)
at Zone.run (zone.js:142)
at NgZone.runOutsideAngular (core.es5.js:3844)
at AngularEchartsDirective.createChart (angular-echarts.directive.js:30)
at AngularEchartsDirective.onOptionsChange (angular-echarts.directive.js:65)
at AngularEchartsDirective.ngOnChanges (angular-echarts.directive.js:50)
at checkAndUpdateDirectiveInline (core.es5.js:10831)
at checkAndUpdateNodeInline (core.es5.js:12330)
at checkAndUpdateNode (core.es5.js:12269)

I followed these steps for install:

  • add npm packages in package.json

      "echarts": "^3.7.2",
      "ngx-echarts": "^1.2.4"
    
  • include this lines in my webpack.common.js file :

    plugins: [
      new webpack.ProvidePlugin({
        echarts: "echarts"
      })
    ]
    
  • include this line in my shared module:
    import { AngularEchartsModule } from 'ngx-echarts';

  • call in my shared component:
    <div echarts [options]="chartOption"></div>

I'm using angular 4.2.6

Thanks in advance

angular cli 打包问题

{
  "scripts": [
    // ...

    // add this:
    "../node_modules/echarts/dist/echarts.js" or "../node_modules/echarts/dist/echarts.min.js"
  ],
}

不用压缩的echarts.js打包根本就不能看。。。打包完script.js 2M多
要介绍一下吧

示例很卡

看过几个echarts示例,这个界面感觉很卡不知道是ui的原因还是示例本身有问题

Navigation issue on chart click

Hello,
The navigation failed when i try to navigate after click on chart

public chartClicked(e: any): void { this.router.navigate(['/page/home']); }

<div echarts [options]="optionPieWhite" class="demo-chart-2" (chartClick)="chartClicked($event)"></div>

This is an issue from ngx-echarts or angular 4 ?

Thank for your response.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.