Bjorn Liza
Bjorn Liza

Reputation: 109

How to render dynamic data in mat-header-cell row with Angular

I'd like my headers to be rendered through an API call. The first time I hard-coded them and then realised that I'd need to use an API call so that I give the table more features such as column-by-column filtering.

I'm working on an app revamp and in that previous project, I used an HTML table which had its headers called through an API.

<!-- Empty row first group -->
      <ng-container matColumnDef="header-row-first-group">
        <th mat-header-cell *matHeaderCellDef [attr.colspan]="2">
        </th>
      </ng-container>

      <!-- dynamically rendered headers -->
      <ng-container matColumnDef="header-row-second-group">
        <th mat-header-cell *matHeaderCellDef [attr.colspan]="2" *ngFor="let title of titles; let i = index"> {{title}} <br> </th>
      </ng-container>


      <tr mat-header-row
        *matHeaderRowDef="['header-row-first-group', 'header-row-second-group']; sticky: true">
      </tr>
      <tr mat-header-row *matHeaderRowDef="displayedColumns; sticky: true"></tr>
      <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
    </table>

In the "dynamically rendered headers" comment that's where I try to call the API and when I run it, I get this error

Uncaught Error: Template parse errors: Can't have multiple template bindings on one element. Use only one attribute prefixed with * ("umnDef="header-row-second-group"> ]*ngFor="let title of titles; let i = index"> {{title}}

Upvotes: 0

Views: 1426

Answers (1)

HDM91
HDM91

Reputation: 1396

Can't use two template binding on one element in Angular as in this post explained before: How to apply multiple template bindings on one element in angular

instead you should wrap your container, and use *ngFor like this:

<ng-container *ngFor="let title of titles">
  <ng-container  matColumnDef="header-row-second-group">
    <th mat-header-cell *matHeaderCellDef [attr.colspan]="2" > {{title}} <br> </th>
  </ng-container>
</ng-container>

Upvotes: 1

Related Questions