管道这东西,能够让用户的体验变得好,也能够省去咱们一些重复性的工做;linux
官方的内置管道就不解释了,自行看文档吧typescript
通常是用于Mustache语法的双向数据内,eg: {{item | json}}
json
上面的例子是用了内置的JsonPipe
管道,有人说管道带参数怎么搞?,eg :{{item |slice:0:4 }}
数组
管道后面冒号跟随的就是参数, 也许还有人问如何多重管道调用? eg :{{item | slice:0:4 | uppercase}}
ui
这里看出来了么,这是使用了数据流的概念,用过linux管道的小伙伴一看就知道了。spa
item
的输入数据给slice
处理后再丢给uppercase
处理,最终返回的指望的结果集。code
// 自定义管道必须依赖这两个
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 {
}
}
复制代码
实现一个切割字符串而后拼接...
的管道【用于渲染数据过长截取】orm
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]实现数据截取,悬浮看到完整的数据cdn
// 功能管道
import { SliceStrPipe } from './SliceStr/slice-str.pipe';
@NgModule( {
imports: [
CommonModule
],
declarations: [
SliceStrPipe // 管道生效必须放到declarations里面
],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
复制代码
咱们这边,是写了一组管道,而后放到一个自定义模块里面,最后导出blog
在其余模块引入这个模块就能直接使用了。
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>
复制代码
// 引入日期转换管道
import { TransDatePipe } from '../../../../../widgets/mit-pipe/TransDate/trans-date.pipe';
// 使用自定义管道处理ts内的数据
const PublishDate: new TransDatePipe().transform(res.Data.PublishDate) || '',
复制代码
管道的写法并不复杂,复杂的是你想要在管道内实现怎么样的功能,考虑拓展性,可读性,复用性!
有不对之处请留言,会及时修正,谢谢阅读。