Angular分类筛选异常:仅首次筛选有效,切换分类后元素消失
问题分析与解决
问题现象
商品分类筛选仅能生效一次,切换其他分类后所有商品消失,需刷新页面才能再次筛选。
代码片段
HTML
<form [formGroup]="form"> <select formControlName="category" (change)="filterProductsCategory()"> <option *ngFor="let category of allProductsCategories" [value]="category"> {{category}} </option> </select> </form> <div *ngFor="let product of allProductList" class="different"> <div> {{product.title}} </div> </div>
TypeScript
export class AllProductsComponent implements OnInit { public form: FormGroup; public allProductsCategories: string[] = ["electronics", "jewelery", "men's clothing", "women's clothing"]; public allProductList: IProduct_model[]; ngOnInit(): void { this.form = new FormGroup({ category: new FormControl(null) }) this.productService.getAllProducts().subscribe(value => { this.allProductList = value; }) } public filterProductsCategory(): void { const categoryOptionValue = this.form.controls['category'].value; this.allProductList = this.allProductList.filter(el => el.category === categoryOptionValue); }
问题根源
你每次筛选时直接修改了allProductList本身:第一次筛选后,这个数组里只剩下当前选中分类的商品;当切换其他分类时,你是用已经被过滤过的数组再去筛选,自然找不到匹配的商品,最终数组为空。
解决方法
需要保留一份原始的完整商品数据副本,每次筛选都基于原始数据重新过滤,而不是修改原始数组。具体修改如下:
- 新增变量存储原始商品列表:
public originalProductList: IProduct_model[]; // 新增原始数据存储变量
- 在获取数据时同时赋值给原始数组和展示用数组:
this.productService.getAllProducts().subscribe(value => { this.originalProductList = value; // 保存完整原始数据 this.allProductList = [...value]; // 初始化展示数组为原始数据的副本 })
- 修改筛选方法,基于原始数组过滤:
public filterProductsCategory(): void { const categoryOptionValue = this.form.controls['category'].value; // 基于原始数据重新筛选,避免修改原始数据源 this.allProductList = this.originalProductList.filter(el => el.category === categoryOptionValue); }
这样每次切换分类时,都是从完整的商品列表里重新筛选,就能正常展示对应分类的商品了。
内容的提问来源于stack exchange,提问作者Alexandr Boroshenko
相关产品推荐
相关产品推荐

