angular11 引入echarts
1、项目下载echarts的npm包
项目根目录执行命令:
npm install echarts --save
下载成功后项目的package.json文件中的‘dependencies’对象下会自动添加‘echarts’,并标注你下载的版本
"dependencies": { "@angular/animations": "~11.2.1", "@angular/common": "~11.2.1", "@angular/compiler": "~11.2.1", "@angular/core": "~11.2.1", "@angular/forms": "~11.2.1", "@angular/platform-browser": "~11.2.1", "@angular/platform-browser-dynamic": "~11.2.1", "@angular/router": "~11.2.1", "echarts": "^5.3.2", "ng-zorro-antd": "^11.4.2", "rxjs": "~6.6.0", "tslib": "^2.0.0", "zone.js": "~0.11.3" },
2、下载成功后,在你需要绘制图表的组件的ts文件中导入echarts
import * as echarts from 'echarts';
具体使用demo如下:
ts:
import {AfterViewInit, Component, OnInit, ViewChild} from '@angular/core'; import * as echarts from 'echarts'; @Component({ selector: 'app-echart', templateUrl: './echart.component.html', styleUrls: ['./echart.component.less'] }) export class EchartComponent implements OnInit, AfterViewInit { chart: any; @ViewChild('chartTpl') chartTpl; constructor() { } ngOnInit(): void { } ngAfterViewInit(): void {
// 需要等页面加载完成后才能获取页面元素 this.initChart(); } /** * 初始化图表 */ initChart(): void { this.chart = echarts.init(this.chartTpl.nativeElement); /** * 绑定resize */ window.addEventListener('resize', () => { this.chart.resize(); }); this.chart.setOption({ xAxis: { type: 'category', data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] }, yAxis: { type: 'value' }, series: [ { data: [120, 200, 150, 80, 70, 110, 130], type: 'bar', showBackground: true, backgroundStyle: { color: 'rgba(180, 180, 180, 0.2)' } } ] }); } }
html:
<div #chartTpl style="width: 600px;height: 300px"></div>