通过自定义指令在Angular2中使用Echarts (实用)
原文出处:https://blog.****.net/idomyway/article/details/79658099
前言
echarts是第三方js库,不是ts编写,没有类型定义,我们可以引入类型定义的库@types,查询是否有echarts,很高兴其他人已经帮忙实现了。我们只要导入就行。
在网上查询调用ng2调用echarts的方法,比较多的是ngx-echarts和ng2-echarts,这个方法,我都没有走通,在大漠老师的nicefish中有通过自定义指令调用echart的方法,特整理下来。
1. 安装插件
npm install echarts -save
2. 新建指令
ng g d echartDir
在指令中写入以下代码
import { Directive, Input, ElementRef, OnInit } from '@angular/core';
import * as echarts from 'echarts';
@Directive({
selector: '[newChart]'
})
export class NewChartDirective implements OnInit{
@Input('newChart') Option;
constructor(
private el:ElementRef
) { }
ngOnInit(){
console.log(this.el.nativeElement);
echarts.init(this.el.nativeElement).setOption(this.Option);
}
}
3.检查ngModule中是否引入了新建的指令
import { NewChartDirective } from './new-chart.directive';
@NgModule({
declarations: [
NewChartDirective,
…
]})
4.在使用的组件中声明echart配置项
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-echarts-test',
templateUrl: './echarts-test.component.html',
styleUrls: ['./echarts-test.component.css'],
})
export class EchartsTestComponent implements OnInit {
// 指定图表的配置项和数据
option = {
title: {
text: 'ECharts 入门示例'
},
tooltip: {},
legend: {
data:['销量']
},
xAxis: {
data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
},
yAxis: {},
series: [{
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}]
};
constructor() { }
ngOnInit() {
}
}
5.在.html(视图中)使用指令
<div id='chart' [newChart]="option" style="width:500px;height:500px;"></div> 1
运行结果:
注意事项:
import * as echarts from 'echarts'
导入echarts对象后我们就可以参照echarts的api开始使用,这边你可能会奇怪from’echarts’,路径是哪里,其实在tsconfig.json文件中统一定义了根路径typeRoots
{
"compilerOptions": {
...,
"typeRoots": [
"../node_modules/@types"
]
}
}
也就是node_modules文件夹下的路径