鏈接: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 {
}
模仿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';