在每一个项目中,总会有好些地方重复。至于这些复用性较高的代码,可以直接提取出来,封装成一个组件或者服务类。这样方便维护与简洁代码。
1. 创建组件
在根目录下,命令创建
$ ionic g component progress-bar

图片.png
创建成功后,会自动导入到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;/* 进度条背景颜色 */ 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;//总数
@Input()
amount: any;//使用数
length: any;//颜色长度
proportion: any;//比例值
constructor() { this.length = { 'width': '0%', 'transition': 'width 1s', '-webkit-transition': 'width 1s'
}
}
ngOnInit() { this.setData();
} /**
* 设置数据
*/
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);//设置延迟,让动画动起来
} /**
* 数据变化
*/
ngOnChanges() { //重新更新数据
this.setData();
}
}3. 调用
如果调用的页面不是懒加载页面,则在app.module导入
如果调用的页面是懒加载页面,则在页面对应的xxx.module导入

图片.png
在需要显示的页面,传入两个参数

图片.png
此外,Input , Output , EventEmitter 可用来实现组件之间的通讯
作者:No刹那光辉
链接:https://www.jianshu.com/p/320f90992376
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
随时随地看视频