【问题标题】:Angular 6 Checkbox FilterAngular 6 复选框过滤器
【发布时间】:2018-10-09 16:21:31
【问题描述】:

我想使用复选框按变量“类别”过滤 JSON 对象(产品)列表。

产品是被关注的:

  {
  'bikeId': 6,
  'bikeName': 'Kids blue bike',
  'bikeCode': 'KB-3075',
  'releaseDate': 'June 28, 2016',
  'description': 'Kids blue bike with stabalizers',
  'category': 'kids',
  'price': 290.00,
  'starRating': 4.8,
  'imageUrl': 'https://openclipart.org/image/2400px/svg_to_png/1772/bike-kid.png'
}

我目前的ngFor循环如下:

   <tr *ngFor="let product of products">
                       <td><img *ngIf='showImage' 
                         [src]='product.imageUrl' 
                        [title]='product.bikeName'
                        [style.width.px]='imageWidth'></td>
                       <td>{{product.bikeName}}</td>
                       <td>{{product.bikeCode}}</td>
                       <td>{{product.releaseDate}}</td>
                           <td>{{product.price}}</td>
                           <td>{{product.starRating}}</td>
</tr>

我当前的复选框如下:

 <input type="checkbox" name="All" value="true" /> Mens 
                <input type="checkbox" name="All" value="true" /> Womens 
                <input type="checkbox" name="All" value="true" /> Kids 

我问这个问题是因为我整天都在搜索论坛无济于事。有些答案确实回答了它,但是当我测试代码时,它要么已经过时,要么就是不起作用。任何帮助,将不胜感激。

【问题讨论】:

  • 触发一个方法来循环您的对象数组并按“类别”将它们分组到提供给您的 ngfor 的数组中,该数组会填充您的 products 对象数组的列表。 ....或者您是否要求有人为您这样做?你试过什么?
  • 感谢您的帮助,感谢您的帮助。我试过了吗?是的。敌意是不必要的。
  • Aidan - 抱歉并不是要被解释为敌意,只是询问。干杯!

标签: typescript checkbox angular6


【解决方案1】:

很惊讶你在网上找不到一个例子,因为有很多方法可以解决这个问题,我的答案只是一个。

在此示例中,我保持产品来源不变,但创建第二个数组,其中包含显示的产品。我将每个复选框绑定到过滤器模型的一个属性,当发生更改时,我调用filterChange() 以从该模型更新我的过滤产品数组。

您不一定需要 NgModel 和两个绑定,并且您当然可以从数组中动态生成过滤器,随着应用程序的增长,这可能是一个好主意。你也可以使用 Observables,或者创建一个 Pipe 来过滤 NgFor 中的数组。真正的可能性是无穷无尽的。

MyComponent.ts

export class MyComponent {
  filter = { mens: true, womens: true, kids: true };
  products: Product[] = []
  filteredProducts = Product[] = [];

  filterChange() {
    this.filteredProducts = this.products.filter(x => 
       (x.category === 'kids' && this.filter.kids)
       || (x.category === 'mens' && this.filter.mens)
       || (x.category === 'womens' && this.filter.womens)
    );
  }
}

MyComponent.html

<tr *ngFor="let product of filteredProducts"> <!-- ... --> </tr>
<!-- ... --->
<input type="checkbox" [(ngModel)]="filter.mens" (ngModelChange)="filterChange()" /> Mens 
<input type="checkbox" [(ngModel)]="filter.womens" (ngModelChange)="filterChange()" /> Womens 
<input type="checkbox" [(ngModel)]="filter.kids" (ngModelChange)="filterChange()" /> Kids

【讨论】:

  • 谢谢回复,意思是分配。就在我拥有所有代码的时候,filteredProducts = [] = [];我收到一个错误:'property bikeid is missing type undefined' 任何帮助将不胜感激。
  • 我在定义数组时错误地使用了尖括号。更新了答案。
  • 非常感谢,看起来可能不是,但它帮助分配,希望它可以帮助其他人。
  • 确实,它也帮助了我。答案清晰、快速且易于理解,并且对问题和答案都投了 +1 票:)
猜你喜欢
  • 1970-01-01
  • 2019-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-27
  • 2019-09-13
  • 2021-10-23
  • 1970-01-01
相关资源
最近更新 更多