0

I'm very new to ng-class and I need to have a default class always applied to a span and add another class when a certain condition happens

<span
    [ngClass]="{'timeString': true, 'disabledText': conditionalExpression}">
</span>

My css contains:

.timeString{
    width: 50px;
}

.disabledText {
    color: rgba(0, 0, 0, 0.38);
}

I have checked similar questions but not found what I'm looking for.

Basically I want to get rid of the 'timeString': true part

Mauricio Gracia Gutierrez
  • 10,288
  • 6
  • 68
  • 99

2 Answers2

3

You can try this

<span class="timeString" [ngClass]="{'disabledText': conditionalExpression}"></span>
laiju
  • 1,353
  • 10
  • 17
1

Another approach is to pass an array of classes


// you would add more classes when needed somewhere in your component
// based on your logic

public myClassList = ['timeString'];

<span [ngClass]="myClassList"> </span>

Lukasz Gawrys
  • 1,234
  • 2
  • 8
  • the listClass is dynamic, so I would have to keep it updated in a property or similar ? so for more complex scenarios this could be useful – Mauricio Gracia Gutierrez Aug 27 '21 at 20:42
  • 1
    Yes, that would be a property in your component and you can add or remove so multiple classes without adjusting the template. – Lukasz Gawrys Aug 28 '21 at 10:31
  • the issue in my case is that the expresion to evaluate is quite complex, it depends on many variables, and keeping a propery updated, each time any variable is updated is quite complex at this time. So having the condition on the template is better at this time Thanks – Mauricio Gracia Gutierrez Aug 28 '21 at 14:30
  • It's the same with the condition in template. It will be evaluated all the time when angular change detection runs. As for my example you can also use a function ```getClassList()``` where you put your conditional logic and return the array. But if you have just one dynamic class the accepted answer is just fine. – Lukasz Gawrys Aug 28 '21 at 15:49
  • I'm not talking about when it gets evaluated, I'm talking that current code depends on a lot of boolean flags that are set in MANY methods and keeping the list of classes of updated will be a lot of unwanted work. Also never call methods from an Angular Template - https://betterprogramming.pub/why-you-should-never-use-methods-inside-templates-in-angular-497e0e11f948 – Mauricio Gracia Gutierrez Aug 28 '21 at 19:49