Restructure the display of instantiated elements in *ngFor

43 views Asked by At

I am currently just adding randomized numbers to an array and displaying them to the user.

     <div *ngFor="let temp of randomIntArray; let i = index">
          <div *ngIf="i == randomIntArray.length - 1">
            This is the real random number {{ temp }}
            <div>
              <button (click)="addRandomValueIntoRandomIntArray()">
                add random number
              </button>
            </div>
          </div>

          <div *ngIf="i != randomIntArray.length - 1">
            {{ temp }}
          </div>
     </div>

I think I understand what's happening here as I am creating a new element on the DOM each time the user clicks : addRandomValueIntoRandomIntArray() as its increasing the length of the randomIntArray.

Due to the: *ngIf="i == randomIntArray.length - 1 this will always be the last element and will be always be displayed at the bottom. Is there any feasible way for me to to swap them around and have all the new elements created at the bottom going downwards instead? Below is an image of how it currently looks.

enter image description here

1

There are 1 answers

4
Borad Akash On

You can reverse the order of ngFor items using randomIntArray.slice().reverse()

and you need to change ngIf condition to i==0.

app.component.html

<div *ngFor="let temp of randomIntArray.slice().reverse(); let i = index">
  <div *ngIf="i ==0">
    This is the real random number {{ temp }}
    <div>
      <button (click)="addRandomValueIntoRandomIntArray()">
        add random number
      </button>
    </div>
  </div>

  <div *ngIf="i != randomIntArray.length - 1">
    {{ temp }}
  </div>
</div>