在Angular中,可以使用数组过滤器来过滤数组并只返回匹配的值。以下是一个示例代码:
HTML模板:
- {{item}}
Angular组件:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
- {{item}}
`,
})
export class AppComponent {
items: string[] = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
searchTerm: string = '';
}
自定义过滤器:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {
transform(items: string[], searchTerm: string): string[] {
if (!searchTerm) {
return items;
}
searchTerm = searchTerm.toLowerCase();
return items.filter(item => item.toLowerCase().includes(searchTerm));
}
}
在上面的代码中,我们首先在HTML模板中定义了一个文本输入框,用于输入搜索关键字。然后使用ngModel指令将输入框的值与组件中的searchTerm属性进行双向数据绑定。
在ul元素中,我们使用ngFor指令来遍历items数组,并使用自定义的filter管道对数组进行过滤,只返回匹配的值。
最后,我们在组件中定义了一个名为FilterPipe的自定义过滤器。该过滤器实现了PipeTransform接口,并实现了transform方法来进行过滤操作。在transform方法中,我们首先检查searchTerm是否为空,如果为空则直接返回原始数组。否则,我们将searchTerm转换为小写,并使用数组的filter方法来筛选出包含searchTerm的元素。
请注意,为了使用自定义过滤器,我们需要在NgModule中将其声明和导出。在这个例子中,我们假设FilterPipe类被包含在名为AppModule的NgModule中。要启用自定义过滤器,我们需要将其添加到AppModule的declarations数组和exports数组中。
这样,当用户输入搜索关键字时,只有与关键字匹配的项目将被显示在列表中。
上一篇:Angular数组的变化检测
下一篇:Angular数组和ngFor