Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

AngularJS ng-class if-else expression

With AngularJS I'm using ng-class the following way:

<div class="bigIcon" data-ng-click="PickUp()" 
ng-class="{first:'classA', second:'classB', third:'classC', fourth:'classC'}[call.State]"/>


I'm wondering if I can use the if-else expression to do something similar to this:

<div class="bigIcon" data-ng-click="PickUp()" 
ng-class="{first:'classA', second:'classB', else:'classC'}[call.State]"/>


So whenever call.State differs from first or second use classC and avoid specifying each value?
by

3 Answers

aashaykumar
you could try by using a function like that :

<div ng-class='whatClassIsIt(call.State)'>

Then put your logic in the function itself :

$scope.whatClassIsIt= function(someValue){
if(someValue=="first")
return "ClassA"
else if(someValue=="second")
return "ClassB";
else
return "ClassC";
}
sandhya6gczb
Use nested inline if-then statements (Ternary Operators)

<div ng-class=" ... ? 'class-1' : ( ... ? 'class-2' : 'class-3')">

for example :

<div ng-class="apt.name.length >= 15 ? 'col-md-12' : (apt.name.length >= 10 ? 'col-md-6' : 'col-md-4')">
...
</div>
pankajshivnani123
This is the best and reliable way to do this. Here is a simple example and after that you can develop your custom logic:

//In .ts
public showUploadButton:boolean = false;

if(some logic)
{
//your logic
showUploadButton = true;
}

//In template
<button [class]="showUploadButton ? 'btn btn-default': 'btn btn-info'">Upload</button>

Login / Signup to Answer the Question.