JobPlus知识库 IT 软件开发 文章
ionic3应该善用组件和指令

ionic3开发框架是angular4,所以了解一下angular4的一些基础知识,能让你更好的开发应用。

angular4提供了很多功能强大的内置指令,但在现实情况中,这些内置指令可能还不能完全满足实际要求,这时我们就需要编写自定义指令来实现特定要求。

其实ionic3(angualr4)和ionic2(angular2)差不多,但和ionic1(angular1)就差别非常大了,可以说基本是推倒了重来。在angular1时代,组件和指令是一回事,即严格来说,没有组件这概念,只有指令,而到了angular2时代,虽说组件仍是一种特殊的指令,但已经有一定目的明显区分开来,分别用Directive和Component来标识,用cli生成命令就如下所示:

ionic g directive 指令名

ionic g component 组件名
要说指令和组件的区别,简单说是不带视图和带视图的区别,直观效果是:一个为原有标签动态添加功能,另一个为新建自定义功能标签,详细上有不少细节上的不同。

往往很多人会封装组件,但不会去封装指令,而选择用Provider或者Pipe(管道,相当于angular1时的过滤器filter),甚至样式来实现,虽说这也能解决部分问题,但不是最优的,Directive、Componet、Provider、Pipe都有其专业适用场景,如结构性指令(下面会说),就不好用Provider和Pipe来处理。


Directive——指令

三种分类:


1.属性指令

属性指令指的是以属性形式使用的指令,如ngModel、ngClass、ngStyle等。


2.结构指令

结构指令,用于修改DOM结构。其实就是模版指令,如ngIf,当条件为true时,该元素会被添加到DOM中。其主要依赖TemplateRef和ViewContainerRef来完成操作。TemplateRef用来访问组件的模板,而ViewContainerRef可作为视图内容渲染器,将模板内容插入至DOM中。


3.组件

这个不必说了,我们用得最多的便是组件。与其他指令不同,它描述的是一个视图,是用户可以直接看到的东西。


自定义属性指令

实例:创建一个bgColor属性指令,支持传入颜色名参数,设置目标标签的背景色

1)创建指令。cli使用如下命令创建基本指令,会生成bg-color.ts文件:


ionic g directive bgColor

2)修改指令。在构造函数constructor加上一句,赋值默认颜色:


import { Directive, Input, ElementRef  } from '@angular/core';


@Directive({

  selector: '[bg-color]' // Attribute selector

})

export class BgColorDirective {

  constructor(private el: ElementRef) {

     this.el.nativeElement.style.backgroundColor = 'red';

  }

}

基于安全性考虑,angualr2的文档是建议用Renderer来代替ElementRef使用,有兴趣的可以自行了解下Renderer

3)使用指令

如果调用的页面用了懒加载,在调用指令的页面module.ts里导入指令并声明,反之,在app.module.ts里导入指令并声明,这样调用的组件就能识别该指令了:


import { BgColorDirective } from '../../directives/bg-color/bg-color';


@NgModule({

  declarations: [

    ContactPage,

    BgColorDirective

  ],

  ...

})

在ContactPage.html里这样使用即可查看效果:


<button ion-button bg-color>

   test

 </button>

4)指令扩展,支持输入参数。

上述指令是一个很简单的指令,且很不灵活,因为颜色写死为red了,实际上我们使用场景应该支持多种颜色。那我们这样修改:


import { Directive, Input, ElementRef  } from '@angular/core';


@Directive({

  selector: '[bg-color]' // Attribute selector

})

export class BgColorDirective {


  defaultColor: string ='red';   //默认颜色


  @Input('bg-color')

  set backgroundColor(color:string){

    this.setStyle(color);

  };


  constructor(private el: ElementRef) {

    this.setStyle(this.defaultColor);

  }


  private setStyle(color: string){

    this.el.nativeElement.style.backgroundColor = color;

  }

}

改动的只是用@Input装饰器修饰,然后用set方法触发获得值后的操作。

我们在组件html里就可以这样调用了:


  <button ion-button bg-color="green">

    test

  </button>


5)指令扩展,支持事件操作
我们增加一个点击事件响应操作,点击时,循环切换背景色。为实现该功能,我们需要在事件处理函数上添加@HostListener装饰器,代码改动如下:

import { Directive, Input, ElementRef, HostListener  } from '@angular/core'; @Directive({  selector: '[bg-color]' // Attribute selector }) export class BgColorDirective {  defaultColor: string ='red';   //默认颜色  bgColor: string;    //背景颜色  @Input('bg-color')  set backgroundColor(color:string){    this.setStyle(color);    this.bgColor = color;  };  constructor(private el: ElementRef) {    this.setStyle(this.defaultColor);  }  private setStyle(color: string){    this.el.nativeElement.style.backgroundColor = color;  }  @HostListener('click')  onClick(){    let color: string = this.el.nativeElement.style.backgroundColor == this.defaultColor ? this.bgColor :  this.defaultColor;    this.setStyle(color);  } }

效果图为:我懒得做gif,你想象一个点击循环切换背景色的按钮吧。


自定义结构指令

实例:山寨一个*ngIf的的收缩显示指令,仅为了起到抛砖引玉效果。

为实现该指令,要借用TemplateRef和ViewContainerRef,TemplateRef用来访问组件的模板,而ViewContainerRef可作为视图内容渲染器,将模板内容插入至DOM中。


import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';


@Directive({

  selector: '[expand]' // Attribute selector

})

export class ExpandDirective {


  @Input('expand')

  set condition(newCondition:boolean){

    if(!newCondition){

      this.viewContainer.createEmbeddedView(this.templateRef);

    }else {

      this.viewContainer.clear();

    }

  }

  constructor(private templateRef: TemplateRef<any>, private viewContainer:ViewContainerRef){

}

}

同样别忘了在module里引入后,再在html里使用:

 <div *expand="isExpand">    <button ion-button>test</button>  </div>  <div *expand="!isExpand">     一段文字  </div>

效果图不上了,留待你们试验,哇咔咔。


Component——组件


ionic g component ContentEmpty

关于component,太多文章讲了,这里我不详细说明,主要就两个装饰器:@Input、@Output,分别用于属性和事件绑定。对于事件,使用EventEmitter发送参数即可。直接上代码:


组件ts部分:


import { Component, Input, Output, EventEmitter } from '@angular/core';


@Component({

  selector: 'content-empty',

  templateUrl: 'content-empty.html'

})

export class ContentEmptyComponent {


  @Input() btnWorkText: string = '';    //加载成功后按钮文字

  @Output() onDoWork: EventEmitter<any> = new EventEmitter();

  constructor() {

}


  doWork($event){

    this.onDoWork.emit($event);

  }

}

组件html部分:


    <button ion-button *ngIf="btnWorkText" color="blue" round outline small (click)="doWork($event)" >

        {{btnWorkText}}

    </button>

同样在module里引入后,在html如下调用即可:


<content-empty [btnWorkText]="" (onDoWork)=""></content-empty>

总结:可以看出来,自定义指令和组件不算复杂,只是大家都没有要去封装的概念。如果几乎不需要复用的东西,直接用内置指令实现就好了,否则就要考虑自定指令了,能让你的项目结构更清晰化,至于选择哪种,自己静下心来想一下就好了。


如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!

¥ 打赏支持
225人赞 举报
分享到
用户评价(0)

暂无评价,你也可以发布评价哦:)

扫码APP

扫描使用APP

扫码使用

扫描使用小程序