Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can ngClass use ternary operator in Angular 2?

In Angular 1, the code below works well.

<div ng-class="$varA === $varB ? 'css-class-1' : 'css-class-2'"> 

But when I try to do similar thing in Angular 2. It does not work.

I already added directives: [NgClass]

<div [ngClass]="varA === varB ? 'css-class-1' : 'css-class-2'"> 

How should I write in Angular 2, thanks!

EDIT: It was my mistake, I accidentally added { } to the whole varA === varB ? 'css-class-1' : 'css-class-2'. So ngClass still can use ternary operator in Angular 2.

like image 208
Hongbo Miao Avatar asked Feb 05 '16 17:02

Hongbo Miao


People also ask

What does ngClass do in Angular?

AngularJS ng-class Directive The ng-class directive dynamically binds one or more CSS classes to an HTML element. The value of the ng-class directive can be a string, an object, or an array. If it is a string, it should contain one or more, space-separated class names.

Why we should not use ternary operator?

They simply are. They very easily allow for very sloppy and difficult to maintain code. Very sloppy and difficult to maintain code is bad. Therefore a lot of people improperly assume (since it's all they've ever seen come from them) that ternary operators are bad.

Can I use both class and ngClass in Angular?

yes , you can do it. Did you try it? What happened? You can use both class and ngClass as the first one gives you the opportunity to apply a class that you want to implement in all cases under any circumstances and the later to apply classes conditionally.

How do you give ngClass a condition?

To add a conditional class in Angular we can pass an object to ngClass where key is the class name and value is condition i.e., true or false as shown below. And in the above code, class name will be added only when the condition is true.


1 Answers

Yes. What you wrote works:

<div [ngClass]="varA === varB ? 'css-class-1' : 'css-class-2'"> 

Plunker

The result of the expression on the the right-hand side has to evaluate to one of the following:

  • a string of space-delimited CSS class names (this is what your expression returns)
  • an Array of CSS class names
  • an Object, with CSS class names as keys, and booleans as values

Maybe you had some other error in your code?

like image 75
Mark Rajcok Avatar answered Sep 20 '22 12:09

Mark Rajcok