在Angular 6中过滤带有复选框的列表

时间:2019-04-23 22:24:52

标签: json angular filter pipe

我有很多餐馆

 restaurants=[
{ restname: "rest1", isDelivery: true, isItalian:false, isBreakfast:true},
{ restname: "rest2", isDelivery: false, isItalian:true, isBreakfast:true},
{ restname: "rest3", isDelivery: true, isItalian:false,isBreakfast:false}]

我用* ngFor给他们看:

 <div *ngFor="let rest of restaurants" >
 <p> {{rest.restname}} <p>

,还有一个复选框列表,用于按类别过滤餐厅:

 <p *ngFor="let cat of categories">
  <input type="checkbox" [(ngModel)]="cat.checked" > {{cat.cat}}
</p>

.ts

 categories=[
{ cat: "Delivery", checked: false},
{ cat: "Italian Food", checked: false},
{ cat: "Breakfast Service", checked: false}]

我的主要问题是,如何通过复选框选择一个管道来按一个或多个类别过滤餐馆?

1 个答案:

答案 0 :(得分:0)

您可以在组件中使用函数进行过滤:

<div *ngFor="let rest of getFilteredRestaurants()" >
 <p> {{rest.restname}} <p>
public getFilteredRestaurants() {
  return this.restaurants.filter(r => this.isRestaurantVisible(r));
}

private isRestaurantVisible(restaurant: Restaurant) {
  const validCategories = this.categories.filter(c => c.checked).map(c => {
    switch(c.cat) {
      case 'Delivery': return 'isDelivery';
      case 'Italian Food': return 'isItalian';
      case 'Breakfast Service': return 'isBreakfast';
      default: return null;
    }
  });

  return validCategories.some(c => restaurant[c] === true);
}

请注意,这可能会导致性能问题,因为这些计算将在每个变更检测周期进行-您可能希望实现某种形式的缓存。