?一伪嫁、管道優(yōu)點(diǎn)
(1)可以使用戶的體驗(yàn)變得好
(2)可以省去一些重復(fù)性的工作
二领炫、管道的常規(guī)使用
- 一般是用于 Mustache 語(yǔ)法(插值語(yǔ)法)的雙向數(shù)據(jù):
{{ item | json }} // 內(nèi)置的 JsonPipe 管道 - 管道帶參數(shù)
{{ item | slice:0:4 }} // 管道后面冒號(hào)跟隨的就是參數(shù)
- 多重管道調(diào)用
{{ item | slice:0:4 | uppercase }}
這是使用了 "數(shù)據(jù)流" 的概念,用過 Linux 管道的小伙伴一看就知道了张咳。
item 的輸入數(shù)據(jù)給 slice 處理后再丟給 uppercase 處理帝洪,最終返回的結(jié)果集就是切割后并且轉(zhuǎn)為大寫字符的數(shù)據(jù)。
三脚猾、自定義管道
// 自定義管道必須依賴 Pipe 和 PipeTransform
import { Pipe, PipeTransform } from '@angular/core';
// 管道裝飾符 葱峡, name就是管道名稱
@Pipe({ name: 'name' })
export class PipeNamePipe implements PipeTransform {
// value : 就是傳入的值
// ...args : 參數(shù)集合(用了...拓展符),會(huì)把數(shù)組內(nèi)的值依次作為參數(shù)傳入
// ...args可以改成我們常規(guī)的寫法(value:any,start:number,end:number)
transform(value: any, ...args: any[]): any {
}
}
實(shí)現(xiàn)一個(gè)切割字符串然后拼接...的管道【用于渲染數(shù)據(jù)過長(zhǎng)截取】
import { Pipe, PipeTransform } from '@angular/core';
?
@Pipe({
name: 'SliceStr'
})
?
export class SliceStrPipe implements PipeTransform {
/**
* 截圖字符串字符
* option(start,end,[+str])
*/
// start和end及extraStr后面都跟隨了一個(gè)問號(hào),代表這個(gè)為可選參數(shù)而不是必選的
// 功能就是拼接自定義的字符串(...)等
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;
}
?
}
}
四龙助、如何使一個(gè)自定義管道生效 ★★★
- 單一引入生效
// 功能管道
import { SliceStrPipe } from './SliceStr/slice-str.pipe';
?
@NgModule( {
imports: [
CommonModule
],
declarations: [
SliceStrPipe // 管道生效必須放到declarations里面
],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
- 模塊引入
如果寫了一組管道砰奕,然后放到一個(gè)自定義模塊里面,最后導(dǎo)出泌参。在其他模塊引入這個(gè)模塊就能直接使用了脆淹。
import ..........
const pipe = [
IsCitizenIDPipe,
IsEmailPipe,
IsEnhancePasswordPipe,
IsFixedPhonePipe,
IsLicensePipe,
IsMobilePhonePipe,
IsNormalPasswordPipe,
IsNumberPipe,
IsUsernamePipe,
SliceStrPipe,
TimeDifferencePipe,
TransDatePipe,
ThousandSeparationPipe
];
// 這里是重點(diǎn)
@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';