【问题标题】:Angular material table access tbody角材料表访问tbody
【发布时间】:2020-12-23 18:26:36
【问题描述】:

我在我的一个项目中使用来自@angular/materialmat-table。我需要访问<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>

它会生成这样的 HTML:

我的问题是:如何访问tbody 标签来添加一些项目特定的属性?

它不适用于 CSS 样式。否则,它会很简单。我只需要它有attr="value"

【问题讨论】:

    标签: angular html-table angular-material html-tbody


    【解决方案1】:

    您可以执行以下操作。使用ViewChild 和角度生命周期钩子AfterViewInit

    工作stackblitz

    在模板文件中

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

    在 ts 文件中

    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'));
      }
    }
    

    【讨论】:

    • 谢谢。这就是我自己想出的,但认为应该有一种更清洁的方法。
    猜你喜欢
    • 1970-01-01
    • 2015-11-13
    • 2020-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多