将复选框值传递给 Angular 中的数组

Passing checkbox value to array in Angular

我正在研究一种解决方案,其中根据乘客人数生成的每个输入都有额外的复选框。我想传递每个复选框的值并将其绑定到旁边的输入。计划最终得到一个数组,其中我有输入字段的值 + 每个复选框的值。我不确定如何推进这个。现在,我有:

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

感谢您的帮助!

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

为 child 和行李使用名称为 属性 和布尔属性的数组,并仅在更新乘客数量时重新生成数组,保留之前的乘客。

这是一个有效的 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);
      }
    }
  }