TGrif
TGrif

Reputation: 5921

Angular custom Pipe declaration

I am trying to use a custom Pipe to filter a list of items.

// pipes/my-filter/my-filter.ts

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

@Pipe({
  name: 'my-filter',
})
export class MyFilter implements PipeTransform {
  transform(value: string, ...args) {
    return value;
  }
}

I would like to use it in a page Component that display that list.

// pages/mymodule-liste/mymodule-liste.html

<ion-content>
    <ion-searchbar
      placeholder="Find"
      [(ngModel)]="myInput">
    </ion-searchbar>
    <button ion-item *ngFor="let item of listItem | myFilter: myInput"">
</ion-content>

I try to import the Pipe to the Component

// pages/mymodule-liste/mymodule-liste.ts

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { MyFilter } from '../../pipes/my-filter/my-filter';

@IonicPage()
@Component({
  selector: 'page-mymodule-liste',
  templateUrl: 'mymodule-liste.html',
})
export class MymoduleListePage {
  listItem: any
  constructor(
      public navCtrl: NavController,
      public navParams: NavParams,
      public myFilter: MyFilter) {
  }    
}

But I get this error:

Error: Template parse errors: The pipe 'myFilter' could not be found

I also try to declare it as providers in mymodule-list.module.ts, or globaly in my app.modules.ts declarations and providers but still doesn't work.

I take a look at Angular documentation about Pipe, as well as other stackoverflow answers but can't find a way to make it work.

So my question is how to declare/register a custom Pipe in Angular (v4.1.0) / Ionic (v3.3.0) for use in a specific component?

Upvotes: 0

Views: 2752

Answers (3)

user28143503
user28143503

Reputation: 1

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

@Pipe({
  name: 'paginate'
})
export class PaginatePipe implements 
PipeTransform {

transform(value: any[], page: 
number, 
pageSize: number): any[] {
if (!Array.isArray(value) || page == 
null || pageSize == null) {
  return value;
}

// Calculate the starting index of 
the data slice
const startIndex = (page - 1) * Page 
size;

// Slice the data array to get the 
relevant page
return value.slice(startIndex, 
startIndex + pageSize);
}

}

Upvotes: 0

Rahul Singh
Rahul Singh

Reputation: 19622

The name of your pipe is my-filter not myFilter.

Also check if the pipe is registered in ngModule in declerations

Upvotes: 0

CharanRoot
CharanRoot

Reputation: 6325

your pipe name is my-filter not myFilter

<ion-content>
    <ion-searchbar
      placeholder="Find"
      [(ngModel)]="myInput">
    </ion-searchbar>
    <button ion-item *ngFor="let item of listItem | my-filter: myInput"">
</ion-content>

Upvotes: 1

Related Questions