1

I'm trying to add multiple classes by ngClass, and I'm confused as to why I can't use ternary operator here.

<div [ngClass]="{'otherClass': otherFlag, classFlag ? 'class--true': 'class--false'}>

I get the following error:

Parser Error: Missing expected } at column 37 in [{'otherClass': otherFlag, classFlag ? 'class--true': 'class--false'}]

I'm aware I can do the following:

<div [ngClass]="{
'otherClass': otherFlag,
'class--true': classFlag,
'class--false': !classFlag
}">

Just trying to understand why I can't use ternary operator here (or maybe I'm doing it wrong). I would appreciate the help in understanding this.

Edit: Thank you for both answers. I mostly understood it thanks to Bryan's answer, but both were helpful.

1
  • 1
    What you have is simply an invalid JavaScript consturct. As your other example shows you need to have an object, and while you can make an expression with a ternary operator that results in an object, your other example is simpler and more readable. Commented Feb 11, 2022 at 12:33

2 Answers 2

3

You can't use ternary operator this way because the value of ngClass is a JavaScript object and your class name is used as a key of the object. The ternary operator can only be used for values, not for keys.

You can do this in a JSON:

{
 "key": condition ? value : otherValue
}

But you can't do that:

{
 condition ? "key" : "otherKey": value
}

To do what you want to do you have to use [class] instead of [ngCLass]. Like that:

<div [class]="classFlag ? 'class--true' : 'class--false'">
Sign up to request clarification or add additional context in comments.

Comments

0

They just can't be combined in that way. Use one or the other. For multi condition use example 3, for tenerary use example 1 or 2.

<div [ngClass]="classFlag === false ? 'class--true' : 'class--false'">
  I will be class false
</div>

<div [ngClass]="classFlag === true ? 'class--true' : 'class--false'">
I will be class true
</div>

<div [ngClass]="{ otherClass: otherFlag === true }">I will be class true</div>

Example: https://stackblitz.com/edit/angular-ivy-hmnctu?file=src%2Fapp%2Fapp.component.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.