royB
royB

Reputation: 12977

ngFor create 2 rows

Using Angular 2 ngFor I'm creating a table.

My problem is that my data array contains elements such that each element should create 2 consecutive rows in the table (Using different fields, The second row is collapsible with more data)

<tbody>
    <tr *ngFor="let element of data; let i = index">
       <th>...<th>
       ...
       <td>...<td>
    </tr>
</tbody>

Problem is that tbody doesn't allow any attribute beside <tr>.

I'm looking for something like

<tbody>
   <template *ngFor="let element of data; let i = index">
       <tr>...</tr> //row 1
       <tr>...</tr> //row 2
   </template>
</tbody>

Upvotes: 32

Views: 20616

Answers (2)

Thacio Pacifico
Thacio Pacifico

Reputation: 69

I faced it the same problem and i didn't find any good solution. But after a deep reseach i found this ng-container and it worked very well. U can see it in action bellow

https://plnkr.co/edit/F8ohXKLHvvbHXAqGESQN?p=preview

 <ng-container *ngFor="let obj of posts">
        <tr>
            <td>
                <button (click)="openCloseRow(obj.id)">
                    <span *ngIf="rowSelected!=obj.id; else close">Open</span>
                      <ng-template #close>
                        <span>Close</span>
                        </ng-template>
                </button>
            </td> 
          <td>{{obj.date}}</td>
          <td>
              {{obj.subject}}
          </td>
          <td>{{obj.numComents}}</td>
        </tr>
        <tr *ngIf="rowSelected==obj.id">
            <td></td>
            <td colspan="4">
                <table class="table table-striped">
                    <thead>
                        <tr>                                   
                            <th style="width:15%;">Comment</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr *ngFor="let q of obj.comments">                                  
                            <td style="width:15%;">{{q}}</td>
                        </tr>
                    </tbody>
                </table>
            </td>
        </tr>
      </ng-container>

Upvotes: 4

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657058

That exists with slightly different syntax:

<template ngFor let-element [ngForOf]="data" let-i="index">
   <tr>...</tr> //row 1
   <tr>...</tr> //row 2
</template>

or

<ng-container *ngFor="let element of data let i=index">
   <tr>...</tr> //row 1
   <tr>...</tr> //row 2
</ng-container>

update for >= 4.0.0 <template> was changed to <ng-template>

<ng-template ngFor let-element [ngForOf]="data" let-i="index">
   <tr>...</tr> //row 1
   <tr>...</tr> //row 2
</ng-template>

Upvotes: 51

Related Questions