Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 816
Arron Avatar asked Apr 28 '16 11:04

Arron


People also ask

How do you call a pipe from a component?

If you want to call the pipe directly within the component class, you need to instantiate it and call its tranform method: @Component({ (...) })

Can we use pipe in component Angular?

You don't have to duplicate your code if you want to also use a pipe's functionality in a component class. All you have to do really is inject the pipe like a service, and then call its transform method. The following works for any Angular 2+ app.

How do you create a custom pipe in Angular?

Steps Involved In Creating a Custom Pipe In Angular are: 1) Create a Pipe Class and decorate it with the decorator @Pipe. 2) Supply a name property to be used as template code name. 3) Register your Pipe in the module under declarations. 4) Finally, implement PipeTransform and write transformation logic.


2 Answers

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);
  }
  (...)
}
like image 158
Thierry Templier Avatar answered Nov 13 '22 09:11

Thierry Templier


In version rc6 you need to register the pipes you want to use in a module -> declarations

@NgModule({
    declarations: [
        AppComponent ,
        filter
    ]....
like image 22
Pavlo Oliinyk Avatar answered Nov 13 '22 07:11

Pavlo Oliinyk