2

I am using angular6 and trying to implement background color through inline styling in angular table. If i hard code the values, the background color changes but if i try to put it through variable it remain same.

Template:

<ng-container matColumnDef="color">
  <th mat-header-cell *matHeaderCellDef mat-sort-header> color </th>
  <td mat-cell *matCellDef="let element" [ngStyle]="{'background-color':'#element.color'}"> #{{element.color}} </td>
</ng-container>
Jignesh Joisar
  • 13,720
  • 5
  • 57
  • 57
Uahmed
  • 1,847
  • 5
  • 29
  • 45

3 Answers3

3

you can use like that for only set one style then try use like that

public bgcolor = "red";

note not used (-) here instead of use camelcase style

 [style.backgroundColor]="bgcolor"

second way used like that for multiple

public bgcolor = {
    backgroundColor:"orange"
};

[ngStyle]="bgcolor"

for your style used like that

[ngStyle]="{ backgroundColor:'#' + element.color }"



<ng-container matColumnDef="color">
  <th mat-header-cell *matHeaderCellDef mat-sort-header> color </th>
  <td mat-cell *matCellDef="let element" [ngStyle]="{ backgroundColor:'#' + element.color }" > #{{element.color}} </td>
</ng-container>
Jignesh Joisar
  • 13,720
  • 5
  • 57
  • 57
  • yes but i am using datatable so all the data of table in datasource and every column in table will have different table according to the variable – Uahmed Nov 28 '18 at 11:23
  • #{{element.color}} so here the row data will come in element and i have to use element.color which has the color data. – Uahmed Nov 28 '18 at 11:28
  • Thanks, yes the dash was a problem as we use that in css Styling. – Uahmed Nov 28 '18 at 11:36
0

If you wanted to assign variable (selectedElementColor) value to the background color, you can do as follows

[ngStyle]="{'backgroundColor': selectedElementColor}"

If you assign this value based on condition then you can use condition as follows

[ngStyle]="value === selectedValue && {'backgroundColor': selectedElementColor}

Make sure you are using property backgroundColor and not background-color.

Sandeep
  • 499
  • 4
  • 12
0
<span  [ngStyle]="{'background-color': item.color}"> </span>

page service.ts ::

  return {
    'toolbarTitle': 'My Pins',
    'items': [
        {
            'id': 1,
            'color' : 'red',
        },
    ]
};
Fahimeh Ahmadi
  • 813
  • 8
  • 13