【问题标题】:Filtering a list using checkboxes in angular 9使用角度 9 中的复选框过滤列表
【发布时间】:2020-11-30 21:21:17
【问题描述】:

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

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”,如果未选中,则为未定义。我想我需要使用vehicle.type === 'car'vehicle.type === 'motorcycle' 或其他东西来过滤它。你有例子吗?

【问题讨论】:

标签: angular forms checkbox filter


【解决方案1】:

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

否则您可以维护用于存储字符串 car 和 motor 的枚举并在过滤器块中使用它

【讨论】:

    【解决方案2】:

    首先,您不应该为表单混合使用 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...

    【讨论】:

      猜你喜欢
      • 2019-11-08
      • 2017-08-16
      • 2018-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-13
      • 2012-06-12
      相关资源
      最近更新 更多