Angular Pipes - One input for two data rows

222 Views Asked by At

I'm building an app that has a data set inside it. I need to create search filters for this data set, and for this I'm using Angular pipes.

The problem is that i would like to check two data fields with one input.

Input: Name

Fields: Invoice Name, Customer Name.

I tried to create 2 separate pipes

Pipe 1:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'invoiceLastNameFilter'
})
export class invoiceLastNameFilterPipe implements PipeTransform {

 transform(openInvoices: any, lastName: any): any {
    if(lastName === undefined || lastName === null) return openInvoices;
        return openInvoices.filter(function(invoice){
            return invoice.Invoice_Last_Name.toLowerCase().includes(lastName.toLowerCase());
        });    
  }

}

Pipe 2:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'customerLastNameFilter'
})
export class customerLastNameFilterPipe implements PipeTransform {

 transform(openInvoices: any, lastName: any): any {
    if(lastName === undefined || lastName === null) return openInvoices;
        return openInvoices.filter(function(invoice){
            return invoice.Customer_Last_Name.toLowerCase().includes(lastName.toLowerCase());
        });    
  }

}

Pipes are called here:

<form>
    <div class="form-group">
        <label for="">Last name:</label>
        <input type="text" class="form-control" name="lastName" placeholder="Enter Last name..." [ngModel]="lastName" (ngModelChange)="lastName = $event">
    </div> 
</form>
<table class="table table-hover table-responsive" id="data-table">
    <thead>
        <tr>
            <th></th>
            <th>Ben</th>
    </tr>
    </thead>
        <tbody>
            <tr *ngFor="let invoice of openInvoices | customerLastNameFilter: lastName | invoiceLastNameFilter: lastName">
                <td>{{ invoice.Invoice_Last_Name }}</td>
                <td>{{ invoice.Customer_Last_Name }}</td>
        </tr>
    </tbody>    
</table>    

Of course, this does not work.

Can anyone help with a solution to this?

Is this even possible?

Thank you!

1

There are 1 best solutions below

0
Prashant M Bhavsar On

Replace below code with your code:

<tr *ngFor="let invoice of (openInvoices | customerLastNameFilter: lastName | invoiceLastNameFilter: lastName)">
                <td>{{ invoice.Invoice_Last_Name }}</td>
                <td>{{ invoice.Customer_Last_Name }}</td>
        </tr>

Added bracket for data and filters.

You can check below article for how to create and use custom pipe in Angular. http://musttoknow.com/create-custom-pipe-use-datatable-ngfor-angular/

Explained how to use custom pipe in ngFor..it will save your time.