Phil Jefferies
Phil Jefferies

Reputation: 33

Angular2 - Custom Pipe for *ngFor to filter results by JSON Value

Today I'm trying to learn about custom pipes. I can get everything to work fine until I reach the part where I create the args for the PipeTransform. No matter what I read online, I can't seem to pick up where I'm off.

View Plunker Example

I was hoping to have a filter I could re-use for each card type, Visa, MC, AMEX, etc. and call it from a variable in the pipe.

*ngFor="let transaction of ('./app/api/transactions.json' | fetch | cardType:['Visa'])"

My problem is here, in the cardtype.pipe.ts file:

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

@Pipe({ name: 'cardType' })

export class CardTypePipe implements PipeTransform {
    transform(value: string, args: string[]): any {

        // I can't figure out the args here...

    }
}

Here is sample data that shows 2 Visa transactions and 1 MC. My goal is to only show VISA card types in a table. I'm calling a JSON file for the data:

[
      {
        "cardType": "Visa",
        "amount": 153.42
      },
      {
        "cardType": "MasterCard",
        "amount": 296.11
      },
      {
        "cardType": "Visa",
        "amount": 74.57
      }
]

My Table:

<table class="table table-hover table-striped">
    <thead>
        <tr>
            <th>Card Type</th>
            <th class="text-xs-right">Amount</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let transaction of ('./app/api/transactions.json' | fetch | cardType:['Visa'])">
            <td>{{ transaction.cardType }}</td>
            <td class="text-xs-right">{{ transaction.amount | currency:'USD':true }}</td>
        </tr>
    </tbody>
</table>

Upvotes: 1

Views: 1522

Answers (1)

Leon Radley
Leon Radley

Reputation: 7682

I think you are putting to much logic in the template. It's far more superior and easy to test if you put that logic in the controller where it belongs.

interface Transaction {
  cardType: 'Visa' | 'MasterCard';
  amount: number;
}

@Component({
  // you know the stuff...
})
class TransactionView {

  transactions: Observable<Transaction[]>;

  ngOnInit() {
    this.http.get('./app/api/transactions.json')
      .map(r => r.json())
      .filter(transaction => transaction.cardType === 'Visa')
      .subscribe(transactions => this.transactions = transactions);
  }
}

Upvotes: 2

Related Questions