|
链接:https://juejin.im/post/58db5b55128fe1006cdf0bb3
angular中,管道的使用
管道一般适用于Mustache语法 的双向数据内, eg{{item |json}} 该例子采用了内置的JsonPipe管道。
若要带参数 则{{item |slice:0:4} 管道后面冒号跟随的就是参数
多重管道如何调用 {{item |slice:0:4|uppercase}}
如何书写一个自定义管道
1 自定义管道必须依赖这2个
import { Pipe, PipeTransform } from '@angular/core';
2 // 管道装饰符 ,name就是管道名称
@Pipe ({name: 'name'})
3 export class PipeNamePipe implements PipeTransform {
// value: 传入的值
// ... args: 参数集合(用了...拓展符),会把数组内的值依次作为参数传入 参数可改成常规的写法(value: any ,start: number, end: number)
transform(value: any, ...args:any[]) : any {}
}
例1 实现一个切割字符串然后拼接...的管道【用于渲染数据过长截取】
import { Pipe, PipeTransform } from '@angular/core';
@Pipe( {
name: 'SliceStr'
})
export class SliceStrPipe implements PipeTransform {
transform(value: string, start?: number, end?: number, extraStr: string) :string {
if (value) {
if (typeof start === 'number' && typeof end === 'number') {
if (value.length > end && extraStr && typeof extraStr === 'string') {
return value.slice(start, end) + extraStr,toString();
} else {
return value.slice(start, end);
}
} else {
return value.slice(start, end)
}
} else {
return value;
}
}
模仿angular中的 keyvalue管道:
import {Pipe, PipeTransform} from '@angular/core';
/*
Convert Object to array of keys.
*/
@Pipe({
name: 'appProperties'
})
export class PropertiesPipe implements PipeTransform {
transform(value: {}): string[] {
if (!value) {
return [];
}
return Object.keys(value);
}
}
在模板中使用: <div *ngFor="let property of response |appProperies>
<div *ngFor="let item of response[property]"> {{item.dosomething}}</div>
</div>
如何是一个自定义管道生效
// 功能管道 , 单一引入生效
import { SliceStrPipe } from './SliceStr/slice-str.pipe';
@NgModule ( {
imports: [CommonModule],'
declarations: [SliceStrPipe], // 管道生效必须放到declarations里面
})
// 模块引入
写一组管道,放到自定义模块中,最后导出,然后在其他模块引入这个模块就能直接使用
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';
来源:https://www.cnblogs.com/xiaogao6681/p/12056271.html |