Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class Binding ternary operator

Tags:

I have some rather cumbersome logic I would like to apply to an element class.

:class="{sportTypes.sports.indexOf(sport) > -1 ? 'is-primary' : 'is-outlined'}"

The above doesn't work, while the following does:

:class="{'is-outlined': sportTypes.sports.indexOf(sport) > -1}"

I get the following error

template syntax error - invalid expression:

Any ideas what's wrong with the first part?

like image 545
softcode Avatar asked Jan 31 '17 23:01

softcode


People also ask

Can we use ternary operator in ngClass?

'css-class-1' : 'css-class-2' . So ngClass still can use ternary operator in Angular 2.

How do I add a class to my ternary operator?

To set className with ternary operator add class 'null' in React, we can set the class name to an empty string. We set className to 'on' if on is true and an empty string otherwise. And we set the the on class to have background color green.

How do I add a class to Vue 3?

Adding a dynamic class name is as simple as adding the prop :class="classname" to your component. Whatever classname evaluates to will be the class name that is added to your component. Join 11,067 other Vue devs and get exclusive tips and insights delivered straight to your inbox, every week.


1 Answers

You have unnecessary braces. The latter expression is an object whereas the first is simply a ternary expression that returns a string.

:class="sportTypes.sports.indexOf(sport) > -1 ? 'is-primary' : 'is-outlined'"
like image 129
Phil Avatar answered Oct 10 '22 16:10

Phil