使用角度9中的复选框过滤列表

问题描述

我需要帮助。 我有车辆清单。无论是汽车还是摩托车,每辆车都有一个值“类型”。我想使用复选框(汽车和摩托车)过滤此列表。我不确定这里的最佳做法是什么。

filter.component.html

<div class="form-group">
      <form class="form-group" [formGroup]="vehiclesFormGroup">
        <label class="custom-control custom-checkbox" >
          <input type="checkbox" class="custom-control-input" formControlName="car" [(ngModel)]="car"/>
          <span class="custom-control-label">Car</span>
        </label>
        <label class="custom-control custom-checkbox" >
          <input type="checkbox" class="custom-control-input" formControlName="motorcycle" [(ngModel)]="motorcycle"/>
          <span class="custom-control-label">Motorcycle</span>
        </label>
        <button class="btn btn-primary btn-block position-sticky btn-search" type="button" (click)="filterVehicles()">Filter Vehicles</button>
      </form>
    </div>


filter.component.ts

 car: false;
 motorcycle: false;
  vehiclesFormGroup = this.formBuilder.group({
    car: this.car,motorcycle: this.motorcycle,})

filterVehicles() {
    console.log('car:',this.car)
    console.log('motorcycle:',this.motorcycle)
  }

如果选中复选框,则控制台输出为“ true”,如果未选中,则控制台输出为undefined。我想我需要通过使用vehicle.type === 'car'vehicle.type === 'motorcycle'或其他方式对其进行过滤。你有例子吗?

解决方法

filter()**方法可根据选中的复选框过滤出车辆的阵列。

在filterVehicle()方法中,使用以下代码:

filterVehicles() {
    console.log('car:',this.car)
    console.log('motorcycle:',this.motorcycle);
    if(this.car){
    this.vehicles= this.vehicles.filter((vehicle) => vehicle.type === 'car');}
    if(this.motorcycle){
     this.vehicles= this.vehicles.filter((vehicle) => vehicle.type === 'motorcycle');
    }
  }

否则,您可以维护用于存储汽车和摩托车字符串的枚举,并将其用于过滤器块中

,

首先,您不应该将ngModel和formControlName绑定混合用于表单。

接下来,您可以订阅表单的valueChanges并在修改复选框后进行过滤:

filteredVehicles = [];
vehiclesFormGroup.valueChanges.subscribe(v => {
let filteredCar = (v.car) ? this.vehicles.filter((vehicle) => vehicle.type === 'car')): [];

let filteredCycle = (v. motorcycle) ? this.vehicles.filter((vehicle) => vehicle.type === 'motorcycle')): [];
this.filteredVehicles = [...filteredCar,...filteredCycle];
})

但是请注意,这种解决方案并不十分优雅,因为如果将来您会有更多的“类型”,您将拥有大量的复制/粘贴/ 在这种情况下,请使用专用功能按字段数组进行过滤。

别忘了退订valueChanges ...

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...