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.
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.
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.
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.
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.
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:
Maybe you had some other error in your code?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With