david moeller
david moeller

Reputation: 365

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

Upvotes: 1

Views: 3821

Answers (3)

Vala Khosravi
Vala Khosravi

Reputation: 2570

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.

Upvotes: 1

Martin Parenteau
Martin Parenteau

Reputation: 73791

You can use the following syntax to set the class given by card.color conditionally:

[ngClass]="{card.color: condition}"

Upvotes: 0

Malindu Sandaruwan
Malindu Sandaruwan

Reputation: 1517

you can use

 ngClass={{card.color}}

Upvotes: 0

Related Questions