How to create and call a pipe from the component in Angular 2?

Arron picture Arron · Apr 28, 2016 · Viewed 33.4k times · Source

I want to create a dynamic pipe which I am going to call from the component.

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

@Pipe({ name: 'filter', pure: false })
export class filter implements PipeTransform {
  transform(value) {
    this.items1=value;
    this.ticket1 = [];
    if (this.items1.length >0) {
      for (var i = 0; i < this.items1.length; i++) {
        this.ticket1.push(this.items1[i])
      }
    }
  }
}

I want to call this pipe from the component.

Answer

Thierry Templier picture Thierry Templier · Apr 28, 2016

You need to specify it within the pipes attribute of your component

@Component({
  pipes: [ filter ] 
})
export class MyComponent {
  (...)
}

and use it in your template:

{{someArray | filter}}
<div *ngFor="someArray | filter">(...)</div>

Edit

If you want to call the pipe directly within the component class, you need to instantiate it and call its tranform method:

@Component({
  (...)
})
export class MyComponent {
  constructor() {
    let filterPipe = new filter();
    let arr = [ ... ];
    var fiteredArr = filterPipe.transform(arr);
  }
  (...)
}