Angular Custom Pipe Kullanımı

Angular 2+’ da .html templatelerimizdeki karakter(string), sayı veya tarih gibi verileri formatlama veya dönüştürmek için custom pipe yazabiliriz.

Bu örneğimizde ” Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print,” metninin Lorem ksımını atıp geri kalanını template ‘de göstermek için custom pipe yazacağız.

ilk önce new-custom.pipe.ts adıyla bir ts dosyası oluşturuyoruz.

import { PipeTransform, Pipe } from "@angular/core";

@Pipe({ name: 'newCustomPipe' })
export class newCustomPipe implements PipeTransform {
  constructor() {
  }

  public data:string=null;
  transform(value:string) :string {    //return type' ta string olarak dönecek.
    this.data=value.substring(5);
    return this.data;
  }
}
// En basit Custom Pipe örneği. Angular Modulede declarations' a eklemek lazım.

Daha sonra app.module.ts ‘ de custom pipe’ ı tanımlıyoruz.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { newCustomPipe } from './new-custom.pipe.ts';

@NgModule({
  declarations: [
    AppComponent,
    newCustomPipe
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Template’ te de aşağıdaki gibi newCustomPipe’ ı kullanıyoruz.

<table class="row-border hover" >
  <thead>
    <tr>
      <th>#</th>
      <th>Description</th>
      <th>Time</th>
      <th>Student</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let item of sessions;let i = index">
      <td>{{ i + 1}}</td>
      <td>{{item?.description | newCustomPipe}}</td>
      <td>{{item?.time | date: 'dd/MM/yyyy HH:mm'}}</td>
      <td>{{item?.first_name}} {{item?.last_name}}</td>
    </tr>
  </tbody>
</table>

Parametreli Custom Pipe

Eğer template’ den parametrede göndermek istiyorsak şu şekilde yaparız.

import { PipeTransform, Pipe } from "@angular/core";

@Pipe({ name: 'newCustomPipe' })
export class newCustomPipe implements PipeTransform {
  constructor() {
  }

  transform(value:string, before: string, after: string) :string {
    let newStr = `${before} ${value} ${after}`;
    return newStr;
  }
}
<td>{{item?.description | newCustomPipe :"Satır Başı":"Satır Sonu"}}</td>

Custom pipe yazmamız gerekli olan durumlarda nasıl bunu oluşturcağımızı öğrendik. Başarılar …