100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > 通过自定义指令在Angular2中使用Echarts

通过自定义指令在Angular2中使用Echarts

时间:2024-08-19 16:14:17

相关推荐

通过自定义指令在Angular2中使用Echarts

前言

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-ponent.html',styleUrls: ['./echarts-ponent.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>

运行结果:

注意事项:

import * as echarts from 'echarts'

导入echarts对象后我们就可以参照echarts的api开始使用,这边你可能会奇怪from’echarts’,路径是哪里,其实在tsconfig.json文件中统一定义了根路径typeRoots

{"compilerOptions": {...,"typeRoots": ["../node_modules/@types"]}}

也就是node_modules文件夹下的路径

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。