下面是一个使用Angular 6和TypeScript实现动态数组过滤器的示例代码:
filter.pipe.ts
的管道文件,并将以下代码添加到该文件中:import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {
transform(items: any[], field: string, value: string): any[] {
if (!items) {
return [];
}
if (!field || !value) {
return items;
}
return items.filter(item => item[field].toLowerCase().includes(value.toLowerCase()));
}
}
FilterPipe
,例如在app.module.ts
文件中:import { FilterPipe } from './filter.pipe';
@NgModule({
declarations: [
// ...
FilterPipe
],
// ...
})
export class AppModule { }
filter
管道来过滤动态数组。例如,在组件的HTML模板中:
- {{ item.name }}
在上述示例中,我们通过使用filter
管道来动态过滤items
数组。我们将绑定到ngModel
的searchValue
作为过滤器的输入。我们还指定要根据name
字段进行过滤。
这样,当用户在输入框中输入时,列表将根据输入的值进行动态过滤。
希望这个示例对你有帮助!