【问题标题】:how to highlight a column in the material data table based on a certain condition on load如何根据负载的特定条件突出显示材料数据表中的列
【发布时间】:2018-05-30 21:01:30
【问题描述】:

在角度材料数据表中,我想根据加载时的某些列值突出显示一些行。例如在下面的组件中

@Component({
 selector: 'table-basic-example',
 styleUrls: ['table-basic-example.css'],
 templateUrl: 'table-basic-example.html',
})
export class TableBasicExample {  
 selectedRowIndex: number = -1;
 displayedColumns = ['position', 'name'];
 dataSource = new MatTableDataSource<Element>(ELEMENT_DATA);

 highlight(row) {
  this.selectedRowIndex = row.id;    
 }
}

export interface Element {
 name: string;
 position: number;     
 }

const ELEMENT_DATA: Element[] = [
 {position: 1, name: 'Hydrogen' },
 {position: 2, name: 'Helium'  },
 {position: 3, name: 'Lithium'}
 ];

html 模板看起来像

<div class="example-container mat-elevation-z8">
<mat-table #table [dataSource]="dataSource">

<!-- Position Column -->
<ng-container matColumnDef="position">
  <mat-header-cell *matHeaderCellDef> No. </mat-header-cell>
  <mat-cell *matCellDef="let element"> {{element.position}} </mat-cell>
</ng-container>

<!-- Name Column -->
<ng-container matColumnDef="name">
  <mat-header-cell *matHeaderCellDef> Name </mat-header-cell>
  <mat-cell *matCellDef="let element"> {{element.name}} </mat-cell>
</ng-container>

<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
  <mat-row *matRowDef="let row; columns: displayedColumns;"  
  [ngClass]="{'highlight': selectedRowIndex == row.id}" 
    (click)="highlight(row)"></mat-row>
  </mat-table>
  </mat-table>
</div>

我可以在点击时突出显示一行,但我们如何根据条件在加载时进行操作。例如如果表中的名称列包含Helium,则突出显示一行

【问题讨论】:

    标签: angular angular-material


    【解决方案1】:

    您可以为此使用 ngClass。将其添加到表格代码的底部:

      <mat-row *matRowDef="let row; columns: displayedColumns;"
      [ngClass]="{'highlight': selectedRowIndex == row.id, 'name_highlighter': row.name === 'Helium'}"
      (click)="highlight(row)">
      </mat-row>
    

    在你的 CSS 中:

    .name_highlighter {
        background-color: red;
    }
    

    【讨论】:

    • ngClass 指令稍微修改为[ngClass]="{'highlight': selectedRowIndex == row.id, 'highlighted': row.name==='Helium' }",似乎可以正常工作
    猜你喜欢
    • 2021-04-25
    • 1970-01-01
    • 2018-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-14
    相关资源
    最近更新 更多