如何解决使用角度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 ...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。