【问题标题】:Filter a list with checkboxes in Angular 6在Angular 6中过滤带有复选框的列表
【发布时间】:2019-09-13 04:04:34
【问题描述】:

我有很多餐馆

 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}]

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

【问题讨论】:

  • 您可以使用响应式表单 API,因为您使用的是 angular

标签: json angular filter pipe


【解决方案1】:

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

<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);
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-17
    • 1970-01-01
    • 2013-05-20
    • 2013-09-16
    • 2019-04-05
    • 2019-05-15
    相关资源
    最近更新 更多