【问题标题】:Access columns in a dynamic generated Material Table in Angular访问 Angular 中动态生成的材料表中的列
【发布时间】:2020-08-28 16:06:20
【问题描述】:

我已经用代码创建了一个动态材质表

    <mat-table matSort [dataSource]="dataSource">
  <ng-container [matColumnDef]="col" *ngFor="let col of displayedColumns">
  <mat-header-cell mat-sort-header *matHeaderCellDef>
              {{col | uppercase}}
  </mat-header-cell>
  <mat-cell *matCellDef="let element">
              {{element[col]}}
  </mat-cell>
  </ng-container>
  <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
  <mat-row *matRowDef="let row; columns: displayedColumns;"
  [ngClass]="row.SEQ % 4 == 0 ? 'rows' : 'row'"></mat-row>
  </mat-table>

我的输出看起来像 -

[![在此处输入图片描述][1]][1]

我想访问名为 xyz 的行,以便在列名下方添加一个小按钮来执行某些功能。

类似的东西-

我怎样才能访问它?谁能帮忙。

【问题讨论】:

    标签: angular


    【解决方案1】:

    方法 #1 没有函数的内联

      <mat-table matSort [dataSource]="dataSource">
        <ng-container [matColumnDef]="col" *ngFor="let col of displayedColumns">
          <mat-header-cell mat-sort-header *matHeaderCellDef>
            {{col | uppercase}}
          </mat-header-cell>
          <mat-cell *matCellDef="let element">
            {{element[col]}}
            <mat-icon *ngIf="col === 'xyz' || col === 'abc'">YOUR_ICON_HERE</mat-icon>
          </mat-cell>
        </ng-container>
      <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
      <mat-row *matRowDef="let row; columns: displayedColumns;"
      [ngClass]="row.SEQ % 4 == 0 ? 'rows' : 'row'"></mat-row>
      </mat-table>
    

    方法#2与函数

    HTML 文件

      <mat-table matSort [dataSource]="dataSource">
        <ng-container [matColumnDef]="col" *ngFor="let col of displayedColumns">
          <mat-header-cell mat-sort-header *matHeaderCellDef>
            {{col | uppercase}}
          </mat-header-cell>
          <mat-cell *matCellDef="let element">
            {{element[col]}}
            <mat-icon *ngIf="shouldDisplayIcon(col)">YOUR_ICON_HERE</mat-icon>
          </mat-cell>
        </ng-container>
      <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
      <mat-row *matRowDef="let row; columns: displayedColumns;"
      [ngClass]="row.SEQ % 4 == 0 ? 'rows' : 'row'"></mat-row>
      </mat-table>
    

    TS 文件

    shouldDisplayIcon(name: string): boolean {
      if (name === 'xyz' || name === 'abc'){
        return true;
      }
      
      return false;
    }
    

    如果此函数将来必须增长,并且如果您决定将其转换为数组或枚举,则函数方式将为您提供更多优势,您可以使用 .includes 或其他属性而不是硬编码进行检查,但因为我可以只看到这段代码我不得不硬编码它。

    如果您想在此处使用图标,请参阅他们在所有图标上的文档https://material.io/resources/icons/?style=baseline

    【讨论】:

    • 感谢您的帮助,您知道如何更改特定列的类吗?就像我想改变一列的宽度一样,我怎么能做到呢?
    • 如果你是动态做的?查看 ng-class
    猜你喜欢
    • 1970-01-01
    • 2020-07-24
    • 2020-09-25
    • 1970-01-01
    • 2021-09-03
    • 2018-09-26
    • 2020-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多