user944513
user944513

Reputation: 12729

how to use pipe in angular 2 js?

I am trying to use pipe or filter in angular 2 js .I need to apply that filter on my list .I want to show only that item (which end with t character).In other words I need to display only that item which end with t

here is my code http://plnkr.co/edit/FKGrBDGyEIc3n2oaWUvf?p=preview

import { Pipe, PipeTransform } from 'angular2/core';

    export class EndWithT implements PipeTransform {
      transform(value: string, exponent: string): string {
        return value
      }
    }

In html

<ion-list style="border:2px solid grey;height:500px">
  <ion-item *ngFor="#item of Todo | EndWithT">
{{item.name}}
<button style='float:right' (click)="deleteTodo(item)">delete</button>
  </ion-item>
</ion-list>

Upvotes: 2

Views: 784

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202176

You need to add the @Pipe decorator to your class:

@Pipe({
  name: 'endWithT'
})
export class EndWithT implements PipeTransform {
  transform(value: string, exponent: string): string {
    return value
  }
}

and add the class name within the pipes attribute of the component / page where you want to use it:

@Page({
  template: `
    <ion-list style="border:2px solid grey;height:500px">
      <ion-item *ngFor="#item of Todo | endWithT">
        {{item.name}}
        <button style='float:right' (click)="deleteTodo(item)">delete</button>
      </ion-item>
    </ion-list>
  `,
  pipes: [ EndWithT ]
})

You also need to update your transform methos this way:

transform(value: string, exponent: string): string {
  if (!value) {
    return value;
  }

  return value.filter((val) => {
    return /t$/.test(val.name);
  });
}

See this plunkr: http://plnkr.co/edit/3TQDQWq84YePtjDsrIgb?p=preview.

Upvotes: 2

Related Questions