How to create custom pipe and use in DataTable or ngFor in Angular
Given simple example of creating custom pipe to filter data based on status of data. Here used data table for listing and pagination of data.
Create pipe file advanced-filter.pipe
import {Pipe, PipeTransform} from '@angular/core'; @Pipe({ name: 'advancedFilters' }) export class AdvancedFilterPipe implements PipeTransform { transform(array: any[], ...args): any { if (array == null) { return null; } return array.filter(function(obj) { if (args[1]) { return obj.status === args[0]; } return array; }); } }
Here, array – will be data array passed to your custom pipe
obj – will be the object of data by using that object you can add condition to filter data
We have added condition obj.status === args[0] so that data will get filter on status which is passed in .html file
Now, import and declare custom pipe in module.ts file of component:
import {AdvancedFilterPipe} from './basic-filter.pipe'; //Declare pipe @NgModule({ imports: [DataTableModule, HttpModule, CommonModule, FormsModule, ChartModule, RouterModule], declarations: [ DashboardComponent, AdvancedFilterPipe], exports: [ DashboardComponent ], providers: [{provide: HighchartsStatic}] })
Use of created custom angular pipe in .html file
<table class="table table-bordered" [mfData]="data | advancedFilters: status" #mf="mfDataTable" [mfRowsOnPage]="rowsOnPage" [(mfSortBy)]="sortBy" [(mfSortOrder)]="sortOrder"> <thead> <tr> <th class="sortable-column" width="12%"> <mfDefaultSorter by="inquiry_originator">Origin</mfDefaultSorter> </th> </tr> </thead> <tbody class="dashboard-grid"> <ng-container *ngFor="let item of mf.data; let counter = index;"> <tr class="data-row {{ item.status }} grid-panel-class-{{ counter }}"> <td class="align-center">{{ item.trn_date }}</td> <td>{{ item.trn_ref }}</td> </tr> </tbody> </table> //If you are using *ngFor and want to use custom angular pipe then below is code <li *ngFor="let num of (numbers | advancedFilters: status"> {{ num | ordinal }} </li>
Hope this helps you to understand how to create custom pipe in angular and how to use with dataTable or ngFor condition.