angularangular-filtersangular2-custom-pipes

Angular custom pipes returns error with table data


component.html:

<input 
  type="text" 
  [(ngModel)]="searchText" 
  placeholder="search your products here" 
  name="searchText">

<table class="table table-bordered">
  <thead>
    <tr>
      <th>Id</th>
      <th>Description</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let obj of product| filter: searchText">
      <td>{{obj.id}}</td>
      <td>{{obj.description}}</td>
    </tr>
  </tbody>
</table>

filter.ts:

transform(items: any, searchText: string): any[] {
  if (!items || !searchText || searchText === undefined) {
    return items;
  }

  return items.filter(items =>
    items.description.toLowerCase().includes(searchText.toLowerCase));
}

console displays items.description is undefined.

model.ts:

export class products{
  id: number;
  description: string;    
}

There is no error till the page loads,once I start typing in searchbox,error is displayed.Error is shown in below code.

<input 
  type="text" 
  [(ngModel)]="searchText" 
  placeholder="search your issues here" 
  name="searchText">

Solution

  • You're not calling searchText.toLowerCase here. You need to call it. Also, you're naming the input and each item as items. That's another issue probably.

    Change your transform implementation to:

    transform(items: any, searchText: string): any[] {
      if (!items || !searchText || searchText === undefined) {
        return items;
      }
    
      return items.filter(item =>
        item.description.toLowerCase().includes(searchText.toLowerCase()));
    }
    

    Unless of course, it's a typo in your OP.

    Here's a Sample StackBlitz for your reference.