在每一個(gè)項(xiàng)目中,總會有好些地方重復(fù)袁辈。至于這些復(fù)用性較高的代碼菜谣,可以直接提取出來,封裝成一個(gè)組件或者服務(wù)類晚缩。這樣方便維護(hù)與簡潔代碼尾膊。
1. 創(chuàng)建組件
在根目錄下,命令創(chuàng)建
$ ionic g component progress-bar
圖片.png
創(chuàng)建成功后荞彼,會自動(dòng)導(dǎo)入到components.module文件冈敛,如果自定義的組件需要用到ionic的組件,則需要在此引入IonicModule
2. 修改組件
.html
<div class="Bars">
<div [ngStyle]="length">
<span>{{proportion}}</span>
</div>
</div>
.scss
div { font-size: 12px; }
#n { margin:10px auto; width:920px; border:1px solid #CCC;
font-size:14px; line-height:30px; }
#n a { padding:0 4px; color:#333 }
.Bar ,.Bars { position: relative; width: 120px;border-radius: 9999px;
/* 寬度 */ border: 1px solid #B1D632; padding: 1px; }
.Bar div,.Bars div { display: block; position: relative;
background:#00F;/* 進(jìn)度條背景顏色 */ color: #333333;
height: 12px; /* 高度 */ line-height: 12px;border-radius: 9999px;
/* 必須和高度一致鸣皂,文本才能垂直居中 */ }
.Bars div{ background:color($colors, primary) ;}
.Bar div span,.Bars div span { position: absolute;width: 120px;
/* 寬度 */ text-align: center; font-weight: bold; }
.cent{ margin:0 auto; width:300px; overflow:hidden}
.ts
import { Component, Input, OnInit, OnChanges } from '@angular/core';
/**
* Generated class for the ProgressBar page.
*
* See http://ionicframework.com/docs/components/#navigation for more info
* on Ionic pages and navigation.
*/
@Component({
selector: 'progress-bar',
templateUrl: 'progress-bar.html',
})
export class ProgressBarComponent implements OnInit, OnChanges {
@Input()
total: any;//總數(shù)
@Input()
amount: any;//使用數(shù)
length: any;//顏色長度
proportion: any;//比例值
constructor() {
this.length = {
'width': '0%',
'transition': 'width 1s',
'-webkit-transition': 'width 1s'
}
}
ngOnInit() {
this.setData();
}
/**
* 設(shè)置數(shù)據(jù)
*/
setData(){
this.proportion = Math.round(this.amount / this.total * 100);
if (this.proportion) {
this.proportion += '%';
} else {
this.proportion = '0%';
}
setTimeout(() => {
this.length.width = this.proportion;
}, 200);//設(shè)置延遲抓谴,讓動(dòng)畫動(dòng)起來
}
/**
* 數(shù)據(jù)變化
*/
ngOnChanges() {
//重新更新數(shù)據(jù)
this.setData();
}
}
3. 調(diào)用
如果調(diào)用的頁面不是懶加載頁面,則在app.module導(dǎo)入
如果調(diào)用的頁面是懶加載頁面寞缝,則在頁面對應(yīng)的xxx.module導(dǎo)入
圖片.png
在需要顯示的頁面癌压,傳入兩個(gè)參數(shù)
圖片.png
4. 效果
2.gif
此外,Input 荆陆, Output 漱贱, EventEmitter 可用來實(shí)現(xiàn)組件之間的通訊
企建網(wǎng)-網(wǎng)站設(shè)計(jì)油额、網(wǎng)站建設(shè)筑凫、SEO推廣營銷、百度排名優(yōu)化鸠儿、系統(tǒng)軟件開發(fā)、微信公眾號、小程序等一站式服務(wù)平臺。