Ionic的便捷之处就是为我们提供了一系列组件,如ion-header、ion-content等。当Ionic2自带的组件不能满足项目需求时,我们便需要自定义组件。
1.使用命令生成自定义组件模版
ionic g component myComponent
此处省略了创建新项目的步骤,不了解的同学请查看之前的文章。ionic-cli提供了很多便捷的操作,比如生成自定义组件模版“ionic g component YourComponentName”,g即generate。
类似的命令还有:
ionic g page YourPageName //创建新页面
ionic g directive YourPageName //创建指令
ionic g component YourComponentName //创建组件
ionic g provider YourProviderName //创建服务
ionic g pipe YourPipeName //创建过滤器
2.组件模版介绍
新建好的组件模版位于“src/components”,组件的结构和Page类似,由html、ts、scss组成。在app.module.ts中声明组件后,即可在项目中使用。
-
my-component.html
1<div class="red-text">{{text}}</div> -
my-component.scss
12345my-component {.red-text{color: red;}} -
my-component.ts
123456789101112131415import { Component } from '@angular/core';@Component({selector: 'my-component',templateUrl: 'my-component.html'})export class MyComponentComponent {text: string;constructor() {this.text = 'My First Component';}}
在其余page中使用如下代码即可。
|
1
|
<my-component></my-component>
|
3.组件通讯之@Input
组件复用时,我们需要在不同的地方实现不同的效果,此时便可引入“@Input”。简单来说,“@Input”从父组件获取数据,输入到当前组件当中。
注意:要在子页面(即组件中)的ts文件中,import引入两个关键词:import { Component,Input,Output,EventEmitter } from '@angular/core';
一个简单的例子
-
my-component.html
1<div class="red-text">来自{{data}}的消息</div> -
my-component.scss
12345my-component {.red-text{color: red;}} -
my-component.ts
123456789101112import { Component,Input } from '@angular/core';@Component({selector: 'my-component',templateUrl: 'my-component.html'})export class MyComponentComponent {@Input('data') data: string;constructor() {}} -
home.html中加入
1<my-component data="HomePage"></my-component> -
about.html中加入
1<my-component data="AboutPage"></my-component>
效果如下
4.组件通讯之@Output
简单来说,“@Output”从当前组件获取数据,输出到父组件当中。
继续修改我们的例子,我们给组件增加一个点击事件,点击后弹出该组件位于哪个页面。
-
my-component.html
1<div class="red-text" (click)="MCClick()">来自{{data}}的消息</div> -
my-component.scss
12345my-component {.red-text{color: red;}} -
my-component.ts
1234567891011121314151617181920import { Component, Input, Output, EventEmitter } from '@angular/core';@Component({selector: 'my-component',templateUrl: 'my-component.html'})export class MyComponentComponent {@Input('data') data: string;@Output() parentClick = new EventEmitter();constructor() {}MCClick() {this.parentClick.emit({from: this.data})}} -
home.html中加入
1<my-component data="HomePage" (parentClick)="onClick($event)"></my-component> -
about.html中加入
1<my-component data="AboutPage" (parentClick)="onClick($event)"></my-component> -
home.ts&about.ts中均添加如下方法:
123onClick(e) {alert(e.from)}
效果如下
本文只是简单介绍自定义组件的用法和与父组件的交互,真实项目可能会比较复杂,但万变不离其宗,相信随着技术的累计,大家会写出功能更加完善的组件。