通过自定义指令在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-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>     

    运行结果:

    这里写图片描述

注意事项:

import * as echarts from 'echarts'

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

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

也就是node_modules文件夹下的路径

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值