Reputation:
I want to know how to define two pipes in the same component. Here, i want to define two transforms in my component. One is already defined -
transaction.component.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'orderBy','filterpipe'
})
export class TransactionComponent implements OnInit ,PipeTransform{
public transform(array: any[], reverse: boolean = false, prop?:
string) {
//code
}
transform(customers: Customer[], args: any[]): any {
return customers.filter(customer =>
customer.email.toLowerCase().indexOf(args[0].toLowerCase()) !== -1);
}
//code
}
But here i am unable to define two names in one pipe.
I get error -
Argument of type '{ name: string; 'filterpipe': any; }' is not
assignable to parameter of type 'Pipe'.
Object literal may only specify known properties, and ''filterpipe''
does not exist in type 'Pipe'.
Upvotes: 2
Views: 8453
Reputation: 11
In Angular 7 (I think newest versions also) you can have several pipes in the same file, adding a new decorator for each one as below.
I'm not sure if is the best practice, but you can do something like:
import {Pipe, PipeTransform, *} from "@angular"
@Pipe({
name: "myPipe1"
})
export class myPipe1 implements PipeTransform {
return null;
}
@Pipe({
name: "myPipe2"
})
export class myPipe2 implements PipeTransform {
return null;
}
Upvotes: 0
Reputation: 1
companyone.pipe.ts
import {Pipe, PipeTransform} from '@angular/core';
import {Company} from './company';
@Pipe({
name: 'companyone'
})
export class CompanyOnePipe implements PipeTransform {
transform(obj: Company): string {
let output = obj.cname+' : '+ obj.location;
return output;
}
}
Upvotes: 0
Reputation: 752
Angular is forcing developers to write one class per file which is a good practice. If you want to create few different Pipe
s you can do it by creating few different files. For example:
@Pipe({
name: 'orderBy'
})
export class OrderByPipe implements PipeTransform{
public transform(array: any[], reverse: boolean = false, prop?:
string) {
//code
}
Other Pipe:
@Pipe({
name: 'filterpipe'
})
export class FilterPipe implements PipeTransform{
public transform(array: any[], reverse: boolean = false, prop?:
string) {
//code
}
You have to add your Pipe
s to module declaration too if you want to use them in your components.
Also be careful about naming your Pipe classes, I can see that you named it TransactionComponent
and it really doesn't have anything to do with any component. Pipe classes should be generic and do only one thing single responsibility.
Upvotes: 2
Reputation: 222582
You cannot define two pipe in same file. you should define two pipe using different files.
@Pipe({
name: 'orderBy'
})
and
@Pipe({
name: 'filterpipe'
})
In HTML, its a sample
<div *ngFor="let l of listings | orderBy:'TEST' | filterpipe:'ACTIVE' ">
Upvotes: 0