ionic3提供的组件已经相当丰富咯,但是事实上有些特殊的需求,比如使用百度地图,或者第三方插件echart报表插件是,就不能用传统的方式去使用第三方插件咯,如何在Ionic3项目中使用第三方JavaScript库?.其实特别简单啦,跟着我步伐前进吧。
1、切换到项目目录全局安装typings
npm install -g typings
2、使用Typings搜索Chart.js
typings search chart.js
如下图找到了3个 我们使用来源是npm的那个
3、在app目录执行
typings install chart.js --source npm
4、安装chart.js依赖
npm install chart.js
在node_modules目录下生成的文件
5、界面代码
<ion-header> <ion-navbar> <ion-title> 图表示例 </ion-title> </ion-navbar> </ion-header> <ion-content> <div padding-vertical> <canvas #chartBar height="200"></canvas> </div> <div padding-vertical> <canvas #chartLine height="200"></canvas> </div> <div padding-vertical> <canvas #chartPie height="200"></canvas> </div> </ion-content>
6、ts代码
import { Component, ViewChild, ElementRef } from '@angular/core'; import { NavController,IonicPage } from 'ionic-angular'; import Chart from 'chart.js'; // 导入chart.js @IonicPage() @Component({ selector: 'page-contact', templateUrl: 'contact.html' }) export class ContactPage { @ViewChild('chartBar') chartBar: ElementRef; @ViewChild('chartLine') chartLine: ElementRef; @ViewChild('chartPie') chartPie: ElementRef; constructor(public navCtrl: NavController) { } ionViewDidEnter() { Chart.Bar(this.chartBar.nativeElement.getContext("2d"), { data: { labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"], datasets: [{ label: '呵呵', data: [12, 19, 3, 5, 2, 3], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } }); Chart.Line(this.chartLine.nativeElement.getContext("2d"), { data: { labels: ["January", "February", "March", "April", "May", "June", "July"], datasets: [ { label: "哈哈", fill: false, lineTension: 0.1, backgroundColor: "rgba(75,192,192,0.4)", borderColor: "rgba(75,192,192,1)", borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: "rgba(75,192,192,1)", pointBackgroundColor: "#fff", pointBorderWidth: 1, pointHoverRadius: 5, pointHoverBackgroundColor: "rgba(75,192,192,1)", pointHoverBorderColor: "rgba(220,220,220,1)", pointHoverBorderWidth: 2, pointRadius: 1, pointHitRadius: 10, data: [65, 59, 80, 81, 56, 55, 40], spanGaps: false, } ] } }); Chart.Doughnut(this.chartPie.nativeElement.getContext("2d"), { data: { labels: [ "Red", "Blue", "Yellow" ], datasets: [ { data: [300, 50, 100], backgroundColor: [ "#FF6384", "#36A2EB", "#FFCE56" ], hoverBackgroundColor: [ "#FF6384", "#36A2EB", "#FFCE56" ] }] } }); } }
7、最后上截图