0

I have a fragment of html code that has to repeat as many times as it comes from a variable, I tried with a ngFor but it doesn't work for me. The variable quantityPiani contains a number (integer) that is passed to it by a service

<form [formGroup]="formPiano">
  <div class="tab">
    <div class="d-flex alert alert-primary sub-container" *ngFor="let q of quantpiani" role="alert">
      <!-- qui va inserito il ciclo for a seconda della quantità sopra riportata -->
      <div class="scheda">
        <div>
          <h3>PIANO</h3>
        </div>
        <div>
          <h5>Livello del piano:</h5>
          <input type="number" name="" id="piano" formControlName="piano" required>
        </div>
        <div>
          <h5>quantità stanze:</h5>
          <select formControlName="stanze">
            <option [ngValue]="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            <option value="5">5</option>
            <option value="6">6</option>
          </select>
        </div>
      </div>
    </div>
  </div>
</form>
<div>
  <button [routerLink]="['/ufficio']" routerLinkActive="router-link-active">Indietro</button>
  <button [routerLink]="['/stanza']" routerLinkActive="router-link-active">Avanti</button>
</div>
Charlie
  • 22,886
  • 11
  • 59
  • 90

1 Answers1

0

The ngFor works with a collection. So, if you want to use it as a for loop, creating a mock array for the directive is one of the possible ways.

Convert the quantityPiani variable to an array which hold symbolic values in your component.

quantityPiani = new Array(quantityPiani).fill(0);     //Create an array of quantityPiani number of elements

Use this array in your ngFor directive:

<div class="d-flex alert alert-primary sub-container" *ngFor="let q of quantPiani" role="alert">

Note: the caps in the quantityPiani variable is corrected in your template code.

Charlie
  • 22,886
  • 11
  • 59
  • 90