[Fixed] Angular, popup menu for each populated row

Issue

Angular 10, I have populated table rows from an array of objects and each row has a button which toggle a popup menu, (There are two buttons in the popup menu) and clicking on those buttons will get the row id and will call a new component. All is good and I can take the id for each row. The problem is that I don’t know how to have it setup that clicking the row button only show one popup for that selected row which should be displayed next to the row (overlay). right now when I click all popup show.

 <table >
    <div *ngFor="let car of car.models">
        <tr>
            <td>
                <div>{{car.amount)}}</div>
            </td>
            <td>
                <div>
                    <div (click)="openPopup()"> <img src="button.png"> </div>

                    <div *ngIf="showPopup"> 
                        <a><div>open page 1</div></a>
                        <a><div>open page 2</div></a>
                    </div>
                </div>
            </td>
        </tr>
    </div>
</table>

And in the TS file:

 openPopup() {
    this.showPopup = !this.showPopup;
  }

Solution

Since showPopup is a single variable, all rows reference the same value. You could either create a new component for each row, which then encapsulates the value of showPopup or make it a list. The latter is shown in this sample code

<div *ngFor="let car of car.models; let index = index">
    <tr>
        <td>
            <div>{{car.amount)}}</div>
        </td>
        <td>
            <div>
                <div (click)="openPopup(index)"> <img src="button.png"> 
            </div>

                <div *ngIf="showPopup[index]"> 
                    <a><div>open page 1</div></a>
                    <a><div>open page 2</div></a>
                </div>
            </div>
        </td>
     </tr>
</div>
showPopup = []
openPopup(index: number) {
    this.showPopup[index] = !this.showPopup[index];
  }

Leave a Reply

(*) Required, Your email will not be published