ng2自定义管道

一、管道的作用及本质

作用:数据处理

本质:公用的方法

二、定义管道组件

//summary.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({
name:
'summary',
// pure: false 管道默认为纯管道,如果加了pure:false 则为非纯管道
  // 纯管道只能检测纯变更(原始类型(String Number Boolean Symbol)值的更改,或者对对象引用(Date Array Function Object)的更改

}) export class SummaryPipe implements PipeTransform { transform(value: number[], args: any[]): any{return value.reduce((prev,next)=>{prev + next}); //数组求和 } }

三、module组件中引入管道

//app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { SummaryPipe} from './summary.pipe';

@NgModule({
  imports: [
    BrowserModule,
    SummaryPipe    //管道引入
  ],
  declarations: [
    AppComponent
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

四、组件中使用管道

// app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: ` <div><span *ngFor="let i of list" >{{i}}&nbsp;</span></div>
<div>{{list | summary:value}}</div>

 

  //模板中使用管道
    <button (click)="addNum()">add 4</button>
  `,
  styleUrls:['./app.component.css']
})
export class AppComponent {
  list: number[] = [1,2,3];
  addNum() {
    this.list.push(4);
  }
}

五、页面效果

1.纯管道

点击按钮之后

2.非纯管道

点击按钮之后从图中可以看出,使用非纯管道实现了累加,而使用纯管道不能实现累加

六、说明

模板中可以在管道后面加冒号:如:

<div>{{list | summary:value}}</div>

这里的value则为传给管道的参数(args

posted @ 2017-06-19 10:52  枫叶布  阅读(1172)  评论(0编辑  收藏  举报