Append the code right after the current index

Issue

I have an add button that allows repeating the code.

  <div *ngFor="let detail of _detailRowNumber">
    <mat-form-field appearance="fill">
      <mat-label>Label of a detail</mat-label>
      <input matInput type="text">
    </mat-form-field>

    <mat-form-field appearance="fill">
      <mat-label>Description of a detail</mat-label>
      <input matInput>
    </mat-form-field>

    <button *ngIf="_detailRowNumber.length > 1" (click)="decreaseDetailRow(detail)" mat-fab color="primary" aria-label="Add a new row for a new detail">
      <mat-icon>remove</mat-icon>
    </button>

    <button (click)="increaseDetailRow()" mat-fab color="primary" aria-label="Add a new row for a new detail">
      <mat-icon>add</mat-icon>
    </button>
  </div>
_detailRowNumber: Array<number> = [0];

increaseDetailRow(): void {
  this._detailRowNumber.push((this._detailRowNumber.length - 1) + 1);
}

Let’s say the code will loop 10 times. My problem is that it appends the code always at the last position, no matter what add button I am clicking on. What I want is to append the code right after the section of the button that has been clicked. How can I do this?

I have also tried it with the following method but I see no difference:

increaseDetailRow(index: number): void {
  this._detailRowNumber.splice(index, 0, index++);
}

Solution

It’s normal for your code to be appended at the last position, since that’s what push does to an array. If you want to insert it in a specific position you’re correct to try the splice of the array and pass the value of the index from the ngFor. That should work, e.g.:

const arr = [1, 2, 3, 4];
arr.splice(1, 0, 3);
console.log(test); - [1, 3, 2, 3, 4]

Here’s a quick example on stackblitz – https://stackblitz.com/edit/angular-ivy-oycdbk?file=src/app/app.component.html. You can see how when you click add button, at the specific position the element with a value index + 1 is successfully added at that position/index, so I think that your splice logic might also work but that you’re looking at it wrong, since there’s not a lot of difference that you can see when you’re rendering the same elements with mocked data.

Answered By – justchecking

Answer Checked By – Jay B. (AngularFixing Admin)

Leave a Reply

Your email address will not be published.