管道这东西,可以让用户的体验变得好,也可以省去我们一些重复性的工作;
官方的内置管道就不解释了。。自行看文档吧复制代码
一般是用于Mustache语法的双向数据内,eg: {{item | json}}
上面的例子是用了内置的JsonPipe管道。。有人说管道带参数怎么搞?,eg :{{item |slice:0:4 }}
管道后面冒号跟随的就是参数, 也许还有人问如何多重管道调用? , eg :{{item | slice:0:4 | uppercase}}
这里看出来了么,这是使用了数据流的概念,用过linux管道的小伙伴一看就知道了。。item
的输入数据
给slice
处理后再丢给uppercase
处理,最终返回的结果集就是切割后并且转为大写字符的数据
// 自定义管道必须依赖这两个
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;
}
}
}
局部代码的写法 --- 这是视图绑定的使用方法,那若是放在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) || '',
// 功能管道
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';
管道的写法并不复杂,复杂的是你想要在管道内实现怎么样的功能,考虑拓展性,可读性,复用性!
下一篇扯下自定义指令的~~~~