当前位置: 移动技术网 > IT编程>脚本编程>AngularJs > Angular2的管道Pipe的使用方法

Angular2的管道Pipe的使用方法

2017年12月12日  | 移动技术网IT编程  | 我要评论

管道pipe可以将数据作为输入,然后按照规则将其转换并输出。在angular2中有许多内置的pipe,比如datepipe、uppercasepipe和currencypipe等。在这里我们主要介绍如何自定义pipe。

1. 管道定义

pipe的定义如下代码所示:

import { pipetransform, pipe } from '@angular/core';

/*users: array<any> = [
  { name: '1', id: 1 },
  { name: '2', id: 2 },
  { name: '3', id: 3 },
  { name: '4', id: 4 },
  { name: '5', id: 5 },
  { name: '6', id: 6 }
];*/

@pipe({ name: 'filteruser' })
export class filteruserpipe implements pipetransform {
  transform(allusers: array<any>, ...args: any[]): any {
    return allusers.filter(user => user.id > 3);
  }
}

如代码所示,

  1. 需要使用@pipe来装饰类
  2. 实现pipetransform的transform方法,该方法接受一个输入值和一些可选参数
  3. 在@pipe装饰器中指定管道的名字,这个名字就可以在模板中使用。

注意:当定义完成后,不要忘记在module的declarations数组中包含这个管道。

2. 管道使用

user.template.html实现如下所示:

<div>
  <ul>
    <li *ngfor="let user of (users | filteruser)">
      {{user.name}}
    </li>
  </ul>
</div>
<button (click)="adduser()"> add new user</button>

user.component.ts实现如下所示:

import { component } from "@angular/core";

@component({
  templateurl: './user.template.html',
})

export class envappcomponent {
  id = 7;
  users: array<any> = [
    { name: '1', id: 1 },
    { name: '2', id: 2 },
    { name: '3', id: 3 },
    { name: '4', id: 4 },
    { name: '5', id: 5 },
    { name: '6', id: 6 }
  ];

  adduser() {
    this.users.push({ name: this.id++, id: this.id++ })
  }
}

在user.component.ts中初始了数据users和定义一个添加user的方法,在user.template.html中使用自定义管道filteruser。

当启动应用时,可以发现只有id大于3的user被显示出来了。可是,当你点击按钮添加用户时,发现并没有什么反应,数据并没有改变。这是为什么呢?

3. 数据变更检测

在angular2中管道分为两种:纯管道和非纯管道。默认情况下管道都是纯管道。

纯管道就是在angular检测到它的输入值发生了纯变更时才会执行管道。纯变更也就是说原始数据类型(如string、number和boolean等)或者对象的引用发生变化。该管道会忽略对象内部的变化,在示例中,数组的引用没有发生改变,改变的只是数组内部的数据,所以当我们添加数据时并没有立即响应在页面上。

非纯管道会在组件的变更检测周期中执行,而且会对对象的内部数据进行检测。

在我们的示例中将管道变更为非纯管道是非常贱简单的,只要在管道元数据中将添加pure标志为false即可。

代码如下所示:

@pipe({ name: 'filteruser', pure: false })
export class filteruserpipe implements pipetransform {
  transform(allusers: array<any>, ...args: any[]): any {
    return allusers.filter(user => user.id > 3);
  }
}

这样每当我们添加新用户时,数据就会马上响应在页面上了。

在根模块声明的pipe在页面中引用有效,而在页面中引用的component中的模板则无效,这也是令我困惑的地方...

寻求了一些解决方案,大多是要注意得在根模块中声明,于是我做了个尝试,将组件也写成一个功能模块,并在组件功能模块中申明pipe,结果很欣喜,组件中的pipe生效了。

具体操作方法:

只需新建组件功能模块,并在改模块中申明pipe,mycomponent.module.ts

import { ngmodule } from '@angular/core';
import { ionicpagemodule } from 'ionic-angular';
import { mycomponent } from 'mycomponent.ts';
import { hellopipe } from "hello.pipe.ts";

@ngmodule({
 declarations: [
  mycomponent,
  hellopipe
 ],

 imports: [
  ionicpagemodule.forchild(mycomponent)
 ],

 exports: [
  mycomponent
 ]
})

export class mycomponent {}

大功告成,组件的模板引用pipe得以生效.

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网