1

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.

5

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.

2

You can use if formula

<div aura:id="myDiv" class="{!if(v.sample != null,'Class1','')}" >

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.