Search code examples
angularjsangularangular6stylingng-style

Angular6 ngStyle to apply style dynamically


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>

Solution

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