在Angular中使用管道过滤一些数据的问题



我有一个下拉框,我在其中添加了一个搜索框,我想根据文本框条目过滤选项。在我的情况下,我也说如果searchText是空或空返回所有的数据,这工作得很好。但是如果我提交一个过滤器,就会得到这个错误。

core.js:6142 ERROR TypeError: Cannot read properties of undefined(读"toLowerCase")在option-filter.pipe.ts: 13:47在数组中。filter ()在OptionFilterPipe。变换(option-filter.pipe.ts: 13:16)

这是我的模板代码
<igx-drop-down-item *ngFor="let option of options |  optionFilter : optionsearch.value : 'name'" [value]="option">
{{ option.name }}
</igx-drop-down-item>

这是我的管道代码

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);
}
}
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);
}
}

应该做,还没有测试

PS:从适当的位置导入serverdropdownnoption

我想在我的情况下,它与何时被调用和没有数据有关,因为它是一个异步调用。Fieldname不是问题,我无法消除,因为它需要告诉函数在对象中过滤哪个字段。

下面是修复问题的代码

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

最新更新