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:

Expanded view:

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>
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With