Angular 2.x折腾记 :(5) 动手实现一个自定义管道

1,892 阅读3分钟

前言

管道这东西,可以让用户的体验变得好,也可以省去我们一些重复性的工作;

官方的内置管道就不解释了,自行看文档吧

管道的常规使用

一般是用于Mustache语法的双向数据内,eg: {{item | json}}

上面的例子是用了内置的JsonPipe管道,有人说管道带参数怎么搞?,eg :{{item |slice:0:4 }}

管道后面冒号跟随的就是参数, 也许还有人问如何多重管道调用? eg :{{item | slice:0:4 | uppercase}}

这里看出来了么,这是使用了数据流的概念,用过linux管道的小伙伴一看就知道了。

item 的输入数据给slice处理后再丢给uppercase处理,最终返回的期望的结果集。

书写一个自定义管道

Demo写法


// 自定义管道必须依赖这两个
import { Pipe, PipeTransform } from '@angular/core';

// 管道装师符 , name就是管道名称
@Pipe({
  name: 'name'
})


export class PipeNamePipe implements PipeTransform {
  // value : 就是传入的值
  // ...args : 参数集合(用了...拓展符),会把数组内的值依次作为参数传入
  // ...args可以改成我们常规的写法(value:any,start:number,end:number)
  transform(value: any, ...args: any[]): any {
    
  }
}

字符串裁剪

实现一个切割字符串然后拼接...的管道【用于渲染数据过长截取】

import { Pipe, PipeTransform } from '@angular/core';


@Pipe({
  name: 'SliceStr'
})
export class SliceStrPipe implements PipeTransform {
  /**
    * 截图字符串字符
    * option(start,end,[+str])
    */
  // start和end及extraStr后面都跟随了一个问好,代表这个为可选参数而不是必选的
  // 功能就是给出截图的启示,然后是否拼接你自定义的字符串(...)等
  transform(value: string, start?: number, end?: number, extraStr?: string): string {
    // console.log( value );
    if (value) {
      if (typeof (start) === 'number' && typeof (end) === 'number') {
        if (value.length > end && extraStr && typeof (extraStr) === 'string') {
          // console.log( start, end, extraStr );
          return value.slice(start, end) + extraStr.toString();
        } else {
          return value.slice(start, end);
        }

      } else {
        return value;
      }
    } else {
      return value;
    }

  }
}

上面的效果图,结合[title]实现数据截取,悬浮看到完整的数据

如何使一个自定义管道生效

单一引入生效

// 功能管道
import { SliceStrPipe } from './SliceStr/slice-str.pipe';

@NgModule( {
  imports: [
    CommonModule
  ],
  declarations: [
    SliceStrPipe  // 管道生效必须放到declarations里面
  ],
  schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})

模块引入

我们这边,是写了一组管道,然后放到一个自定义模块里面,最后导出

在其他模块引入这个模块就能直接使用了。

import ..........


const pipe =  [
  IsCitizenIDPipe,
  IsEmailPipe,
  IsEnhancePasswordPipe,
  IsFixedPhonePipe,
  IsLicensePipe,
  IsMobilePhonePipe,
  IsNormalPasswordPipe,
  IsNumberPipe,
  IsUsernamePipe,
  SliceStrPipe,
  TimeDifferencePipe,
  TransDatePipe,
  ThousandSeparationPipe
];

@NgModule( {
  imports: [
    CommonModule
  ],
  declarations: [
    MitPipeComponent,
    ...pipe,
  ],
  exports: [ ...pipe ],
  schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
export class MitPipeModule { }



// ----- 引入module

// 管道 -- 把MitPipeModule丢到imports里面就行了
import { MitPipeModule } from '../../../../../widgets/mit-pipe/mit-pipe.module';

使用

视图绑定

这是视图绑定的使用方法,那若是放在ts里面如何使用一个管道呢。且看我道来

  <td [title]="item.SupplierName">{{item.SupplierName | SliceStr:0:13:'...' || '' }}</td>

ts内管道处理数据


// 引入日期转换管道
import { TransDatePipe } from '../../../../../widgets/mit-pipe/TransDate/trans-date.pipe';

// 使用自定义管道处理ts内的数据
const PublishDate: new TransDatePipe().transform(res.Data.PublishDate) || '',

效果图

总结

管道的写法并不复杂,复杂的是你想要在管道内实现怎么样的功能,考虑拓展性,可读性,复用性!

有不对之处请留言,会及时修正,谢谢阅读。