為了減少代碼的編寫,將復(fù)用率高的代碼組件化,是angular提倡的一種方式嘲碱。在angular1中兜畸,自定義組件還是比較復(fù)雜的。但是在angular中,就顯得相當(dāng)簡(jiǎn)單。
1.自定義組件
創(chuàng)建一個(gè)ts文件,以引用ionic2+highcharts為例
import {Component,ElementRef,AfterViewInit,OnDestroy,ViewChild,ContentChild} from '@angular/core';
import * as Highcharts from 'highcharts';//引入hightcharts
import {ApiengineService} from '../../providers/apiengine-service/apiengine-service' //自定義的調(diào)用api接口
@Component({
selector:'shop-chart', // 在模版中使用<shop-chart></shop-chart>直接調(diào)用
template: '<div #shopChart></div>',
providers:[ApiengineService]
})
export class ShopChart implements AfterViewInit, OnDestroy{
constructor(public apiengine:ApiengineService){}
//調(diào)用自定義接口涧狮,獲取圖表參數(shù)
loadData():any{
return new Promise((resolve,reject)=>{
this.apiengine.getH("api.assister.shopChartMonth",{}).then(data=>{
if(data['errno'] === 0){
resolve(data['data']);
}
}).catch((err)=>{
reject(err)
})
})
}
@ViewChild("shopChart") public chartEl:ElementRef;
private _chart: any;
ngAfterViewInit(){
this.loadData().then((data)=>{
let opts: any = data;
//本應(yīng)用為webapp,為方便日后對(duì)圖表的更新簇宽,故將hightcharts的主要參數(shù)opts通過api方式獲取
if (this.chartEl && this.chartEl.nativeElement) {
opts.chart.renderTo = this.chartEl.nativeElement;
this._chart = new Highcharts.Chart(opts);
}
});
}
ngOnDestroy() {
this._chart.destroy();
}
}
通過以上勋篓,就可以實(shí)現(xiàn)一個(gè)自定義的組件<shop-chart>
2. 使用
在需要使用的ts文件中,添加以下代碼
import {ShopChart} from '../../shopChart';
在@Component中添加directives
@Component{
...
directives:[ShopChart]
}
再通過@ViewChild方式將組件導(dǎo)入
@ViewChild(ShopChart) shopChart:ShopChart;
最后html部分直接使用
<shop-chart></shop-chart>
3.效果圖
做了個(gè)demo魏割,請(qǐng)忽略圖表
4.遺憾
目前就發(fā)現(xiàn)這個(gè)方式可以順利實(shí)現(xiàn)在segement下切換展現(xiàn)圖表譬嚣。每次切換時(shí)都會(huì)調(diào)用api,感覺不是很好钞它。目前也是初學(xué)angular2拜银,還不能完全理解ViewChild/ViewChildren/ContentChild等的區(qū)別和具體使用方法。后續(xù)有更好的方法將更新遭垛。也希望各位大神能給給出更好的解決方案尼桶。感激不盡。