MurabitoB

Angular 自定義 Pipe

N 人看过

首先要實作 Custom Pipe 必須先繼承 PipeTransform Interface,並實作 transform function

此外,還要定義 @Pipe 的 Decorator

@Pipe({
	name: 'custom'
})
export CustomPipe implements PipeTransform {

	transform(value: any){
		return value.subString();
	}
}

或者直接使用 angular cli

ng g p <pipeName >

然後在需要引用該 pipe 的 module 宣告該 pipe

@NgModule({
  declarations: [
    AppComponent,
    CustomPipe
  ],
  imports: [
    BrowserModule,
    FormsModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})

接著就可以在底下的 componenet 使用該 pipe

<div>{{name | custom }}</div>

引用參數

Pipe 的 transform function 除了把需要被 pipe 操作的內容傳進來之外,也可以追加自訂義參數來參數化操作的類型

transform(value: any, length: number){
	return value.subString();
}

透過給 pipe 後面追加 :參數 就可以設定,此外,如果有多個參數的狀況,可以繼續 chain 下去 ex | custom:a:b:c

<div>{{name | custom:date }}</div>

Pure Pipe

在 Angular 的 Pipe 預設會是 Pure Pipe ,他不會檢查 Object 或 Array 內容的變化,因此會導致綁定的 Array 或 Object 發生變化後,畫面顯示上還是原始的值。

如果要做修正,可以進行以下設定

@Pipe({
	name: 'custom',
	pure: false
})
export CustomPipe implements PipeTransform {

	transform(value: any){
		return value.subString();
	}
}