我正在过滤来自mat-select
的多个选择上的数组。筛选工作正常,除非我选择一个选项,然后取消选择该选项,整个数组将从UI中删除。如果然后选择一些选项,将显示那些数组元素。在同一UI中使用搜索字段输入时,不会发生这种情况。
HTML:
<article *ngIf="monitors">
<div class="title">
<h1>{{title}}</h1>
</div>
<mat-card class="filters">
<mat-form-field class="search">
<input matInput type="text" placeholder="Search Monitors" [(ngModel)]="searchTerm">
<button mat-button *ngIf="searchTerm" matSuffix mat-icon-button
aria-label="Clear" (click)="searchTerm=''">
<mat-icon>close</mat-icon>
</button>
</mat-form-field>
<mat-form-field class="categories">
<mat-select placeholder="Filter categories" [formControl]="categories"
(selectionChange)="filterCategories($event.value)" multiple>
<mat-option *ngFor="let category of categoriesList" [value]="category">{{category}}</mat-option>
</mat-select>
</mat-form-field>
</mat-card>
<mat-card class="list">
<mat-card-content>
<mat-list>
<mat-list-item *ngFor="let monitor of monitors | filter: searchTerm; last as last">
<h2 class="topic" mat-line>{{monitor.topic}}</h2>
<h4 class="description" mat-line>{{monitor.queryDescription}}</h4>
<div class="categories" mat-line>
<span *ngFor="let category of monitor.categories">
{{category.value}}
</span>
</div>
<mat-divider [inset]="true" *ngIf="!last"></mat-divider>
</mat-list-item>
<mat-divider></mat-divider>
</mat-list>
</mat-card-content>
</mat-card>
</article>
TS:
export class MonitorsComponent implements OnInit {
title = 'Monitors';
monitors: IMonitor[];
originalMonitors: IMonitor[];
searchTerm: string;
categories = new FormControl();
categoriesList: string[];
selectedCategories: string[];
constructor(private monitorService: MonitorsService) {}
ngOnInit() {
this.getMonitors();
}
filterCategories(categories: string[]) {
this.monitors = this.originalMonitors.filter((monitor: IMonitor) => {
return categories.some((category: string) =>
monitor.categories.map((c: ICategory) => c.value).includes(category),
);
});
}
}
使用管道时,我得到相同的结果。 取消选择选项后,应该如何重置原始阵列?
编辑:这是一个用来说明我的问题的Stackblitz-https://angular-yehvm6.stackblitz.io 编辑:编辑-https://stackblitz.com/edit/angular-yehvm6
答案 0 :(得分:0)
将点击处理程序更改为此:
filterPizzas(toppings: string[]) {
if(toppings && toppings.length >0){
this.pizzas = this.originalPizzas.filter((pizza: IPizza) => {
return toppings.some((topping: string) =>
pizza.toppings.indexOf(topping) >= 0,
);
});
}else{
this.pizzas = [{ name: 'Cheese Supreme', toppings: ['Extra cheese'] }, { name: 'Meat Feast', toppings: ['Pepperoni', 'Sausage'] }, { name: 'Pizzazz', toppings: ['Extra Cheese', 'Pepperoni', 'Onion'] }]
}
}