简体   繁体   中英

Color cell from mat table angular

I've got this:

Array of objects:

  users : User [];
  average = 5;


compareValue (value){
...}

And im printing a table: like this:

  <table mat-table [dataSource]="users">
    <ng-container matColumnDef="nome">
      <th mat-header-cell *matHeaderCellDef >Name</th>
      <td mat-cell *matCellDef="let element" > {{element.name}} </td>
    </ng-container>

    <ng-container matColumnDef="num_aval">
      <th mat-header-cell *matHeaderCellDef >Number of Works</th>
      <td mat-cell *matCellDef="let element"> {{element.works.length}} </td>
    </ng-container>

    <ng-container matColumnDef="comparaMedia">
        <th mat-header-cell *matHeaderCellDef >Stats</th>
        <td  *matCellDef="let element" > HELP HERE </td>
      </ng-container>


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

  </table>

What I wanna do is the following:

I wanna grab the number of works from an user, compare with the value average (with the function compareValue ), and if the value is under some value, color the cell with blue; if it's above, color the cell with red.

I have no ideia how to do it. Some help?

You can add a class conditionally to your td as

<td mat-cell *matCellDef="let element" [class.red]="element.works.length > average"> {{element.works.length}} </td>

And add styles to your component as

td {
    background-color: blue; /* the default color is blue for the cells */
}

td.red {
    background-color: red; /* more specific style to override color to red */
}

I assume compareValue func returns true if value in cell is higher than average and false when it isn't, so I would use and than use it to setting background color for number of works value cell

<td mat-cell *matCellDef="let element" 
  [style.background-color]="compareValue(element.works.length) ? 'blue' : 'red'"> 
{{element.works.length}} 
</td>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM