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.
If you want to call the pipe directly within the component class, you need to instantiate it and call its tranform method: @Component({ (...) })
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.
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.
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);
}
(...)
}
In version rc6 you need to register the pipes you want to use in a module -> declarations
@NgModule({
declarations: [
AppComponent ,
filter
]....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With