JoseTurron
JoseTurron

Reputation: 243

Set number of HTML inputs depending on variable in Angular

I'm working on a flight reservation system and I'm trying to add inputs in HTML component with a rule that their quantity depends on the chosen number of passengers. So if a user selects that he wants to reserve seats for 5 people, he will have 5 input fields in which he has to put names and surnames of those passengers.

I was trying to use innerHTML with multiplication based on the number given by the user but that did not work.

For now I have 1 input which looks like this:

Passengers data:
    <li><input type="text" [(ngModel)]="passengersData[0]" placeholder="Name and surname"></li>

I was also thinking about using the ngIf but got stuck. Frankly speaking, I am out of ideas how to make it work. Thank you for help in solving this

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

Upvotes: 0

Views: 575

Answers (1)

Dhruv Shah
Dhruv Shah

Reputation: 1661

What you need is basically a way to use ngFor to repetatively render the passenger form for the number of passengers specified.

You can create a function like this in your summary.component.ts:

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

And the update your template to:

<li *ngFor="let passenger of createRange(showStorage.passengersNumber); let i=index"><input type="text" [(ngModel)]="passengersData[i]" placeholder="Name and surname"></li>

Upvotes: 1

Related Questions