Search code examples
javascriptangularinputevent-binding

Passing checkbox value to array in Angular


I'm working on a solution where each of the inputs, generated depending on the passenger number, gets additional checkboxes. I want to pass the value of each checkbox and bind it to the input next to it. The plan is to eventually end up with an array in which I have the value of the input field + each checkbox value. I am not sure how to move forward with this. For now, I have:

COMPONENT.HTML:

<li *ngFor="let passenger of createRange(showStorage.passengersNumber); let i=index"><input type="text" [(ngModel)]="passengersData[i]" placeholder="Name and surname">
<input type="checkbox" (click)="addChild($event)">Child
<input type="checkbox" (click)="addLuggage($event)">Luggage
</li>

COMPONENT.TS

  constructor() {
    this.passengersData = [];
  }

  public passengersData: any[];
  public luggageCounter: number = 0;
  public childrenCounter: number = 0;

  createRange(number){
  var items: number[] = [];
  for(var i = 1; i <= number; i++){
     items.push(i);
  }
  
  return items;
}

  addLuggage(event) {
    console.log("Added luggage");
    this.luggageCounter++
  }

  addChild(event) {
    this.childrenCounter++
    console.log(event);
  }

Thanks for any help!

STACKBLITZ: https://stackblitz.com/edit/flight-date-picker-with-service-done-qfmn6p


Solution

  • Use an array with a name property and boolean properties for child and luggage and regenerate the array only when the number of passengers is updated retaining the previous passengers.

    Here is a working StackBlitz https://stackblitz.com/edit/angular-ivy-s7dtu4?file=src%2Fapp%2Fapp.component.ts

    Number of passengers <input type="text" [ngModel]="passengers.length" (ngModelChange)="updateNumOfPassengers($event)">
    <li *ngFor="let passenger of passengers; let i=index">
      <input type="text" [name]="'name_' + 1" [(ngModel)]="passenger.name" placeholder="Name and surname">
      <input type="checkbox" [checked]="passenger.child" (change)="passenger.child = !passenger.child">Child
      <input type="checkbox" [checked]="passenger.luggage" (change)="passenger.luggage = ! passenger.luggage">Luggage
    </li>
    
      passengers = [];
    
      updateNumOfPassengers(input: string) {
        const numOfPassengers = parseInt(input);
        if (!isNaN(numOfPassengers) && numOfPassengers >= 0) {
          const passengersToAdd = numOfPassengers - this.passengers.length;
          if (passengersToAdd > 0) {
            this.passengers = [...this.passengers, ...Array.from({ length: passengersToAdd }, _ => ({ name: '', child: false, luggage: false }))];
          } else if (passengersToAdd < 0) {
            this.passengers = this.passengers.filter((_, index) => index < numOfPassengers);
          }
        }
      }