2

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!

  • https://stackoverflow.com/questions/52406660/how-to-collapse-as-accordion-json-object-deatails-that-have-ngfor-directive-in – Eliseo Sep 20 '18 at 15:21

3 Answers3

0

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>

David Faure
  • 1,336
  • 14
  • 25
0

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

Yuzam
  • 55
  • 8
0

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>
  • Hi Kevin as a new contributor I remind you to not forget to validate/upvote (or downvote) the answers we provided, accordingly – David Faure Sep 21 '18 at 09:02