5

Is it possible to apply a css class depending on the value of the aura:attribute in a lightning component?

For instance I have the following component.

<aura:component description="JustAComp">
    <aura:attribute name="myAttr" type="Object"/>

    <div aura:id="myDiv">

    </div>
</aura:component>

Now I would like to apply a css class to myDiv if myAttr.prop is not null (or actually I would like to be able to apply a css class depending on boolean expressions composed of the properties of my attribute for example).

Is it possible to do what I want or should I use JavaScript for sure in this case?

Thank you.

2 Answers 2

10

Yes, absolutely. You can use expressions in the class attribute of your Lightning components and HTML elements.

    <div aura:id="myDiv" class="{! v.myBooleanAttribute ? 'my-class-good' : 'my-class-bad' }">

It's common to use the ternary operator ?: as a shorthand when referencing Boolean attributes to embed conditional logic here. You could also compose the class or class list out of multiple elements depending on component attributes.

If you're working with more complex data types, the empty() function will be useful:

An empty argument is undefined, null, an empty array, or an empty string. An object with no properties is not considered empty.

Hence

<div aura:id="myDiv" class="{! empty(v.myListAttribute) ? 'my-class-empty' : 'my-class-full' }">

There's a simple example in the Conditional Expressions section of the Lightning Components Developer Guide using strings, and much more complex examples in the Styling Components section, which demonstrates composing a list of classes conditioned on component attributes.

3

You can use if formula

<div aura:id="myDiv" class="{!if(v.sample != null,'Class1','')}" >
4
  • Is it same way to apply class conditionally in LWC component template? Commented Apr 8, 2020 at 13:24
  • 1
    @sri_bb No, it does not work this way in LWC. Here is how you can do this in LWC. Commented Apr 8, 2020 at 13:30
  • I went through that link already, Was Looking for any other solution to write conditions in template itself? :) Commented Apr 8, 2020 at 15:58
  • @sri_bb that's the only way Commented Apr 9, 2020 at 2:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .