Search code examples
angularngforangular-ng-if

how to show whole table without custom pipe filtering when value is not inserted


How do I rewrite my existing code to show me, when I land on certain page, all the data retrieved from db, and when I enter some value to pipe or to filter that data, show me only what I entered?

<div class="form-group">
    <input type="text" class="form-control" placeholder="Number of beds" [(ngModel)]="num_of_beds" ng-minlength="1">
</div>
<table class="table">
  <thead>
    <tr>
      <th>Room name</th>
      <th>Number of beds</th>
      <th>TV</th>
    </tr>
  </thead>
  <tbody>

        <tr  *ngFor="let room of rooms | SearchPipe:num_of_beds ">

            <td>{{room.roomname}}</td>
            <td>{{room.beds}}</td>
            <td>
                <span *ngIf="room.tv == '1'">
                TV: Yes
                 </span>
            <span *ngIf="room.tv != '1'">
                    TV: No
            </span>
        </td>
        </tr>
  </tbody>

</table>

Here is the pipe :)

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

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

  transform (value, [queryString]) {

        if (value == null) {
            return null;
        }
        console.log('transform');
        return value.filter(item=>item.beds.indexOf(queryString) !== -1);


    }

}

So bassically how to show whole data retrieved from db when i entere in the page and to filter only when i have something submitted whrough the field


Solution

  • you should do like this , check for value of args i.e. querystring if its not present return value without filtering

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({
      name: 'SearchPipe'
    })
    export class SearchPipe implements PipeTransform {
    
      transform(value: any, args?: any): any {
        if(!args)
         return value;
        return value.filter(item=>item.beds.indexOf(args) !== -1);
      }
    }
    

    some what similar : Working Demo