skip to Main Content

I think each table is being populated the size of the test array. Is there a way to only populate each table once on the correct table index?

In the .ts file I have headers and my 2D string array

headers = ['Header1', 'Header2']
test = [['Test1', 'Test2'], ['Test3', 'Test4', 'Test5']]

My HTML looks like this

<ng-container *ngFor="let h of headers; let i = index"
   <h2>{{ h }}</h2>
   <p-table>
      <ng-template p template="body">
         <ng-container *ngFor="let rows of test[i]; let j = index">
            <label>{{rows}}</label>
         </ng-container>
      </ng-template>
   </p-table>
</ng-container>

When I do this my table looks like this:

Header1

Table1
Test1
Test2
Test1
Test2

Header2

Table2
Test3
Test4
Test5
Test3
Test4
Test5

when I want it to display like this:

Table1
Test1
Test2
Table2
Test3
Test4
Test5

2

Answers


  1. I guess you are using loop in a wrong way, Can yu please use this way.

    <ng-container *ngFor="let h of headers; let i = index">
       <h2>{{ h }}</h2>
       <p-table>
          <ng-template p template="body">
             <ng-container *ngFor="let row of test[i]; let j = index">
                <tr>
                   <td>{{ row }}</td>
                </tr>
             </ng-container>
          </ng-template>
       </p-table>
    </ng-container>
    
    Login or Signup to reply.
  2. Since you are using PrimeNG tables, you need to use their syntax:

    <ng-container *ngFor="let h of headers; let i = index">
      <p-table [value]="test[i]" responsiveLayout="scroll">
        <ng-template pTemplate="header">
          <tr>
            <th>{{ headers[i] }}</th>
          </tr>
        </ng-template>
        <ng-template pTemplate="body" let-item>
          <tr>
            <td>{{ item }}</td>
          </tr>
        </ng-template>
      </p-table>
    </ng-container>
    

    StackBlitz here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search