Search code examples
angularangularjs-directiveng-class

Using properties with NgClass directive


Im trying to do something which seems like it should be fairly simple, however I can't find out how to do it and it doesnt seem to be in the docs. Here's a simple example:

<div *ngFor="let card of cards | async">
    <div [ngClass]="{card.color : true}">
    </div>
</div>

Im able to do [ngClass]="[card.color]" or [ngClass]="{'red' : true}"

However, as soon as I try to combine the two I get the following error:Parser Error: Missing expected : at column 6 in [{card.color: true}]

Does anybody have any ideas? Thanks


Solution

  • According to https://angular.io/docs/ts/latest/guide/template-syntax.html

    directiveName - is the shorthand form for structural directives where the long form can only be applied to tags. The short form implicitly wraps the element where it's applied in a .

    [prop]="value" is for object binding to properties (@Input() of an Angular component or directive or a property of a DOM element).

    When you are using [ngClass] what you can bind to it is an expression, in these cases, the common thing is using the conditional operator

    here's the example:

    var c = ((a < b) ? 'minor' : 'major');
    

    The c variable will be minor if the value is true, and major if the value is false.