Search code examples
htmlangularhtml-table

How can I achieve the following table design in angular


I have an array of objects so I'm doing an ng for to display individual objects in that array. But what I'm trying to achieve is that last column shouldn't be part of ngFor row repetition. instead the last student column should only have one row for entire table and the text is centered in the column.

say something like this: enter image description here

https://stackblitz.com/edit/angular-nested-ngfor-in-table-p1wyas?file=src%2Fapp%2Fapp.component.html,src%2Fapp%2Fapp.component.ts,src%2Fapp%2Fhello.component.ts


Solution

  • You can achieve that using the rowspan attribute and *ngIf. Below is a sample of code that can do it. All you have to do is make sure the last col td is only displayed once and it spans all the rows.

    <table class="table table-hover table-striped">
      <thead>
        <tr>
          <th>Discipline</th>
          <th>Course</th>
          <th>Classes</th>
          <th>Students</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let course of disciplines; let ind = index">
          <td>{{ course.count }}</td>
          <td>{{ course.name }}</td>
          <td>{{ course.classes }}</td>
          <td *ngIf="ind == 0" [attr.rowspan]="disciplines.length">
            {{ course.students }}
          </td>
        </tr>
      </tbody>
    </table>
    

    Here is a link for the stackblitz demo for the same