How to add new rows inside of *ngFor loop? I Want to Implement expanding collapsing functionality inside of the table

Issue

I want to implement expand-collapse functionality in my tables. whatever row I clicked the expanded portion should come below of that row only. I’m using angular 2. Without using any other framework how can I do so? I have tried out like below code snippet but whatever be is the row I clicked the new row (Expanded portion) always coming below of all the rows.

Here is the dummy code snippet:

<table>
  <tr>
    <td>column header1</td>
    <td>column header2</td>
    <td>column header3</td>
    <td>column header4</td>
    <td></td>

    <tr *ngFor="let list of pipelines">
      <td>{{list.name}}</td>
      <td>{{list.id}}</td>
      <td>{{list.date}}</td>
      <td>{{list.company}}</td>
      <td><button (click)="ExapndCollapse()">Click to Exapand</button></td>
    </tr>

    <tr>
      <td *ngIf="showExapandedRow">Hello There!</td>
    </tr>

</table>

Solution

Here you go:

.html:

<table>
    <tr>
        <td>column header1</td>
        <td>column header2</td>
        <td>column header3</td>
        <td>column header4</td>
        <td></td>
    </tr>

    <ng-container *ngFor="let list of pipelines">
        <tr>
            <td>{{list.name}}</td>
            <td>{{list.id}}</td>
            <td>{{list.date}}</td>
            <td>{{list.company}}</td>
            <td><button (click)="ExapndCollapse(list.id)">Click to Exapand</button></td>
        </tr>
        <tr>
            <td [ngClass]="{ 'expandedRow': true, 'active': exapandedRowId === list.id }">Hello There!</td>
        </tr>
    </ng-container>

</table>

.ts:

  exapandedRowId: number = 0;
  ExapndCollapse(id) {
    this.exapandedRowId = this.exapandedRowId === id? 0 : id;
  }

.css:

.expandedRow {
  display: none;
}
.expandedRow.active {
  display: block;
}

I’ve created a demo with dummy data HERE.

Answered By – Abdul Rafay

Answer Checked By – Gilberto Lyons (AngularFixing Admin)

Leave a Reply

Your email address will not be published.