ionic 编写自定义控件
- 创建组件
在项目所在目录下执行:
ionic g component <ComponentName>
- 在src/components中会出现:
——components
|——ComponentName
|——ComponentName.html
|——ComponentName.scss
|——ComponentName.ts
|——components.module.ts
- 组件模块:
- ComponentName.html
<div class="progress-outer">
<div class="progress-inner" [style.width]="progress +'%'">
{{showProgress}}%
</div>
</div>
- ComponentName.scss
progress-bar {
.progress-outer{
width: 96%;
margin:10px 2%;
padding: 3px;
text-align: center;
background-color: #f4f4f4;
border:1px solid #dcdcdc;
color: #fff;
border-radius: 20px;
}
.progress-inner{
min-width: 15%;
white-space: nowrap;
overflow: hidden;
padding: 5px;
border-radius: 20px;
background-color: map_get($colors,primary);
}
}
- ComponentName.ts
import {Component, Input} from '@angular/core';
@Component({
selector: 'progress-bar',
templateUrl: 'progress-bar.html'
})
export class ProgressBarComponent {
@Input('progress') progress:Number;
@Input('showProgress') showProgress:Number;
constructor() {
console.log('Hello ProgressBarComponent Component');
}
}
- 组件通讯
- @Input
- @Output
- my.ts:
import {Component, EventEmitter, Input, Output} from '@angular/core';
/**
* Generated class for the MyComponent component.
*
* See https://angular.io/api/core/Component for more info on Angular
* Components.
*/
@Component({
selector: 'my',
templateUrl: 'my.html'
})
export class MyComponent {
@Input('data') data: string;
@Output() parentClick=new EventEmitter();
constructor() {
console.log('Hello MyComponent Component');
}
MCClick(){
this.parentClick.emit({
from:this.data
})
}
}
- my.html:
<div (click)="MCClick()" class="red-text">from {{data}}</div>
- 引入自定义控件
- 在src/app/app.module.ts引入ComponentNameComponent
import { NgModule, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
..........
import {ComponentsModule} from "../components/components.module"
@NgModule({
declarations: [
MyApp,
....
//ProgressBarComponent
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp),
ComponentsModule
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
....
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
export class AppModule {}
- 在使用自定义组件的页面所在的module中引入
...
import {ComponentsModule} from "../../components/components.module"
...
@NgModule({
declarations: [
...
],
imports: [
...
ComponentsModule
]
})
export class MyModule{
...
...
}
- 然后就可以在页面中使用了:
<ion-header>
<ion-navbar>
<ion-title>testProgressBar</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<progress-bar [progress]="loadProgress1" [showProgress]="loadProgress"></progress-bar>
</ion-content>
参考网址:
http://e2web.cn/2017/02/27/
http://blog.csdn.net/github_36704158/article/details/76355989