Angular6 ngStyle to apply style dynamically

7.2k Views Asked by At

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>
3

There are 3 best solutions below

3
On BEST ANSWER

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>
0
On
<span  [ngStyle]="{'background-color': item.color}"> </span>

page service.ts ::

  return {
    'toolbarTitle': 'My Pins',
    'items': [
        {
            'id': 1,
            'color' : 'red',
        },
    ]
};
0
On

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.