Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular ngFor spanning two rows (expand/collapse)

I have an angular application. I need display a list of data in a table. I have applied ngFor on the TR element of the table. However, when each row is expanded, another row with additional details about the item must be displayed.

Collapsed view: enter image description here

Expanded view: enter image description here

Code:

<table>
  <thead>
  <tr>Header here</tr>
  </thead>
  
  <tbody>
    <tr *ngFor="let item of results">
      + Collapsed Row
      <!-- How do I display the expanded row and display additional details when + symbol is clicked? -->
    </tr>
    
  </tbody>
</table>
like image 483
Shilpa Nagavara Avatar asked Feb 05 '26 09:02

Shilpa Nagavara


1 Answers

If you just want a simple expand and collapse row, then a simple ngIf will do the trick:

<tr *ngFor="let item of results">
  <div (click)="item.expanded=!item.expanded">+ Collapsed Row</div>
  <span *ngIf="item.expanded">This is an expanded content</span>
</tr>

However, if you want to have only one row to be expanded at a time, then you need to keep track on which row is expanded.

In your html:

<tr *ngFor="let item of results; let $index=index;">
  <div (click)="expandRow($index)">+ Collapsed Row</div>
  <span *ngIf="$index === expandedIndex">This is an expanded content</span>
</tr>

In your component, initialize a variable called expandedIndex with the value of -1. This ensures all rows are collapsed when the component is inited. You can do it either at constructor level or at ngOnInit, it doesn't really matter:

constructor(public expandedIndex:number){
   this.expandedIndex=-1;
}

Then, have a named function called expandRow:

  expandRow(index: number): void {
    this.expandedIndex = index === this.expandedIndex ? -1 : index;
  }
like image 107
CozyAzure Avatar answered Feb 07 '26 22:02

CozyAzure



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!