Angular material table access tbody

2.7k Views Asked by At

I'm using mat-table from @angular/material in one of my projects. And I need to access <tbody>

    <table mat-table matSort [dataSource]="someSource">

      <ng-container matColumnDef="date">
        <th mat-header-cell *matHeaderCellDef>Date</th>
        <td mat-cell *matCellDef="let some">{{some.field}}</td>
      </ng-container>

      <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>

      <tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>

    </table>

It generates HTML like this: enter image description here

My question is: how can I access tbody tag to add some project-specific attributes?

It's not for CSS styling. Otherwise, it would be simple. I just need it to have attr="value"

1

There are 1 best solutions below

0
On

You can do something like below. Use ViewChild and angular lifecycle hook AfterViewInit

Working stackblitz

In the template file

<table #testtable mat-table [dataSource]="dataSource"> // --> Observe the template reference variable

    ...

</table>

In the ts file

export class TableBasicExample implements AfterViewInit {
  @ViewChild('testtable', {
    read: ElementRef
  }) tble: ElementRef;

  ngAfterViewInit() {
    this.tble.nativeElement.querySelector('tbody').setAttribute('data-title', 'Sivakumar Tadisetti');
    console.log(this.tble.nativeElement.querySelector('tbody'));
  }
}