mardi 11 août 2020

Filtering a list using checkboxes in angular 9

I need help. I have a list of vehicles. Each vehicle has a value "type" whether it is a car or a motorcycle. I want to filter this list using checkboxes (Car and Motorcycle). I am not sure what is the best practice here.

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

The console output is "true" if checkbox is checked and undefined if unchecked. I guess I need to filter it by using vehicle.type === 'car' and vehicle.type === 'motorcycle' or something. Do you have any examples?




Aucun commentaire:

Enregistrer un commentaire