Home > Mobile >  Problem using a Pipe in Angular to filter some data
Problem using a Pipe in Angular to filter some data

Time:05-13

I have a dropdown box where I added a search box to it and I want to filter the Options based on the textbox entry. In my case i also say if searchText is null or empty return all data which works fine. But if I submit a filter I get this error.

core.js:6142 ERROR TypeError: Cannot read properties of undefined (reading 'toLowerCase') at option-filter.pipe.ts:13:47 at Array.filter () at OptionFilterPipe.transform (option-filter.pipe.ts:13:16)

Here is my template code

 <igx-drop-down-item *ngFor="let option of options |  optionFilter : optionsearch.value : 'name'" [value]="option">
    {{ option.name }}
    </igx-drop-down-item>

And this is my pipe code

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

@Pipe({ name: 'optionFilter' })
export class OptionFilterPipe implements PipeTransform {
 
  public transform(data: any[], searchText: any, fieldName: string): any {
  if (searchText == null || data == null || searchText == '' ) {
    return data;
  }
  console.log(data)
  console.log('Serch Text : '   searchText)
  console.log('FieldName : '   fieldName)
   return data.filter(item => item[fieldName].toLowerCase().indexOf(searchText.toLowerCase()) !== -1);
  }
}

CodePudding user response:

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


type DynamicKey = keyof typeof ServerDropdownOption;

@Pipe({ name: 'optionFilter' })
export class OptionFilterPipe implements PipeTransform {
 
  public transform( data: ServerDropdownOption[], searchText: string, fieldName: string ): ServerDropdownOption[] {
  if (searchText == null || data == null || searchText == '' ) {
    return data;
  }
  const fieldRef = fieldName as DynamicKey;
  return data.filter(item => item[fieldRef].toLowerCase().indexOf(searchText.toLowerCase()) !== -1);
  }
}

Should do, Haven't tested

PS: import that ServerDropdownOption from appropriate place

CodePudding user response:

I guess in my case it had to do with when it was called and there was no data since it was a async call. Fieldname was not an issue and i could not elimnate as it is required to tell the function on which field to filter in the object.

Below is code that fixed the issue

return data.filter(item => item[fieldName]?.toString()?.toLowerCase().indexOf(searchText?.toString()?.toLowerCase()) !== -1);
  • Related