htmlangularinputpipes-filters

Angular Custom Pipe with Max - Min amount


So I am trying to create an input for entering in a price, and that input is being filtered with a pipe. Different prices are being received from an API with JSON info.

So for example, If I enter in the price '$300', the results with have each flight that is $300 and below.

I am really bad at writing pipes :( So far the pipe I have attached to it so far filters the input to a degree but I have no clue of how to make it conditional.

https://stackblitz.com/edit/http-get-json?file=app%2FfilterPipe.ts

   <hello name="{{ name }}"></hello>
<p>
    Start editing to see some magic happen :)
</p>
<button (click)="onClick()">Send Request</button>

<div>
  <input type="text" [(ngModel)]="term">
<p>Result:</p>
 <ul>
    <li *ngFor="let group of displayItems">
    {{group.departure.city}}
    <ul>
        <li *ngFor="let flight of group.fares  | filter: term">
        {{flight.price.amount}}
        </li>
    </ul>
    </li>
</ul>
</div>

Here's the Pipe Logic -->

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

    @Pipe({
      name: 'filter'
    })
    export class FilterPipe implements PipeTransform {
     transform(items: any, term: any): any {
        if (term === undefined) return items;

        return items.filter(function(item) {
          for(let property in item){

            if (item[property] === null){
              continue;
            }
            if(item[property].toString().toLowerCase().includes(term.toLowerCase())){
              return true;
            }

           }
          return false;
        });
      }

    }

Solution

  • I have modified your filter pipe as below

    export class FilterPipe implements PipeTransform {
     transform(items: any, term: any): any {
        if (term === undefined) return items;   
        return  items.filter(t=>t.price.amount <= term);;
      }
    
    }
    

    and WORKING DEMO