Search code examples
angularng-class

Angular 6 - How to format [ngClass] when using a variable


I want to add a class based on an item in an object within my components typescript file. I can't seem to get the format correct for this to work.

When the 'selectedColourPalette' value is greater than zero, I want to add the primary colour from 'colourPaletteOne' into the HTML.

CSS

colourPaletteOne = {
    primary: 'blue', 
    secondary: 'grey',    
  }

HTML

<div> [ngClass]="{'border-{{colourPaletteOne.primary}}' : selectedColourPalette > 0}"></div>

Solution

  • You should not use double braces {{ }} when binding to attribute using square brackets []. Therefore, it would be like:

    <div [ngClass]="selectedColourPalette > 0 ? 'border-' + colourPaletteOne.primary : ''"></div>
    

    Edit Note: Changed the ngClass structure, fixed typo

    Update

    If you want to improve the condition checking logic, then you may want to add a method in component and pass the parameters to it, return the desired CSS class as string. Like:

    In template

    <div [ngClass]="getCssClassByPalette(selectedColourPalette, colourPaletteOne)"></div>
    

    In component

    getCssClassByPalette = (scp, cp) => {
    
        let cssClass = '';
    
        swicth(scp){
          case 1: {
             cssClass = cp.primary;
             /* do stuff */
             break; // or return the css class
          }
          /* other cases */
        }
    
        return cssClass;
    }