下面是一个示例,展示了如何使用Angular进行筛选表单:
- {{ product.name }} - {{ product.category }}
// 在组件的类中
import { Component } from '@angular/core';
@Component({
selector: 'app-products',
template: `
`,
styleUrls: ['./products.component.css']
})
export class ProductsComponent {
products: any[] = [
{ name: 'iPhone', category: '电子产品' },
{ name: 'Sofa', category: '家具' },
{ name: 'T-shirt', category: '服装' },
// 其他产品
];
filteredProducts: any[] = [];
filter: any = {};
filterProducts() {
this.filteredProducts = this.products.filter((product) => {
let nameMatch = true;
let categoryMatch = true;
if (this.filter.name) {
nameMatch = product.name.toLowerCase().includes(this.filter.name.toLowerCase());
}
if (this.filter.category) {
categoryMatch = product.category === this.filter.category;
}
return nameMatch && categoryMatch;
});
}
}
在上面的示例中,我们首先在模板中创建了一个表单,包含一个输入框和一个下拉菜单,用于输入筛选条件。然后,我们使用ngModel
指令将输入框和下拉菜单的值与组件中的filter
对象进行绑定。当用户点击"筛选"按钮时,会调用filterProducts
方法。
filterProducts
方法使用Array.filter
函数对产品数组进行筛选。根据filter
对象中的值进行匹配,如果产品名称中包含输入的名称,并且产品类别与选择的类别匹配,就会被保留在filteredProducts
数组中。最后,我们使用*ngFor
指令在页面上循环渲染筛选后的产品列表。
注意:以上示例仅供参考,实际应用中,您可能需要根据自己的需求进行相应的修改。