美文网首页Ios@IONICionic3+Ionic Framework
ionic3 自定义组件 (进度条)

ionic3 自定义组件 (进度条)

作者: No刹那光辉 | 来源:发表于2017-12-26 15:47 被阅读318次

在每一个项目中,总会有好些地方重复。至于这些复用性较高的代码,可以直接提取出来,封装成一个组件或者服务类。这样方便维护与简洁代码。

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
4. 效果
2.gif
此外,Input , Output , EventEmitter 可用来实现组件之间的通讯

相关文章

网友评论

  • 我正年轻:你好,请问一下~我用的ionic3 提示 'progress-bar' is not a known element:blush:
  • 海货:进度对话框没有插件吗?
  • peaktan:楼主,想请问一下,loading 如何实现为一个单利。现在每个页面都要初始化loading 才能使用
    No刹那光辉:@wythetan 建立一个provider服务,所有页面统一调用封装的函数进行显示与隐藏
  • dml1874:<div [ngStyle]="length"> 这个报错:Can't bind to 'ngStyle' since it isn't a known property of 'div'.是什么情况?
    dml1874:@No刹那光辉 好的,我去试试,谢谢😜
    No刹那光辉:@dml1874 你导入IonicModule 模块到components.module试试

本文标题:ionic3 自定义组件 (进度条)

本文链接:https://www.haomeiwen.com/subject/yixjgxtx.html