Search code examples
angularng-class

Angular 4+ ngClass Mix Expressions


I am trying to pass in 2 values to ngClass.

How do you do this:

[ngClass]="'cssprefix-' + var.value, {'newclass' : ifTrue}"

Solution

  • You could move the logic that describes what classes to add to controller's method:

    // controller
    getClasses(ifTrue: boolean, value: string) {
        const ret = {};
        ret['cssprefix-' + value] = true;
        ret['newclass'] = ifTrue;
    
        return ret;
    } 
    
    // in template
    [ngClass]="getClasses(ifTrue, var.value)"
    

    You could also bind to class attribute directly:

    [class]="'cssprefix-' + var.value" [ngClass]="{'newclass' : ifTrue}"
    

    Or use string interpolation:

    class="{{ 'cssprefix-' + var.value }}" [ngClass]="{'newclass' : ifTrue}"