How can I create expand/collapse function for each row of table? Angular6

Viewed 770

So I need to be able to expand some details on each row of a table. Right now I'm having two issues:

  • Clicking the expand/collapse toggle will trigger the action for every row in the table.
  • The first row always puts the details above it.

Here's the code segment:

<tbody>
  <tr *ngFor="let client of clients">
    <td class="details-control">
        <a class="btn btn-link" (click)="collapsed1=!collapsed1">
            <i class="material-icons">
              expand_more
            </i>
        </a>
    </td>
    <td>{{client.firstName}}</td>
    <td>{{client.lastName}}</td>
    <td>{{client.company}}</td>
    <td><input type="checkbox"></td>
  </tr>
  <div *ngIf="!collapsed1">
    <p>Details</p>
  </div>

</tbody>

And what it looks like:

Toggling

Also I had my *ngFor statement in the tag earlier but I realized I can't hit individual client objects if I build a separate for details.

Let me know how I can improve!

3 Answers

It's a very common pattern. The best and quick solution is to use some ID instead of just a boolean in your collapsed1 variable.

<tbody>
 <tr *ngFor="let client of clients">
  <td class="details-control">
    <a class="btn btn-link" (click)="collapsed1 = collapsed1 ? 0 : client.id ">
        <i class="material-icons">
          expand_more
        </i>
    </a>
</td>
<td>{{client.firstName}}</td>
<td>{{client.lastName}}</td>
<td>{{client.company}}</td>
<td><input type="checkbox"></td>
<div *ngIf="collapsed1=client.id">
  <p>Details</p>
</div>

You need a boolean array collapsed[] and use index in your ngFor, so you can use collapsed[i]. Take a look here for using index in ngFor:

ngFor using Index

Let me know if you need more info. Wellcome

Nevermind, here is the code that solved it.

<tbody>
  <tr *ngFor="let client of clients; let i = index">
    <td class="details-control">
        <a class="btn btn-link" (click)="client.hideme=!client.hideme">
            <i class="material-icons" *ngIf="!client.hideme">
              expand_more
            </i>
            <i class="material-icons" *ngIf="client.hideme">
                expand_less
              </i>
        </a>
    </td>
    <td width="30%">{{client.firstName}}
      <tr *ngIf="client.hideme">
        <td>Hey, I'm a bunch of details!</td>
      </tr>
    </td>
    <td>{{client.lastName}}</td>
    <td>{{client.company}}
        <tr *ngIf="client.hideme">
            <td>More Issuer details</td>
        </tr>
    </td>
    <td><input type="checkbox"></td>
  </tr>
</tbody>
Related