4

How can the if condition clause be used in an input helper.

I tried:

{{input class="{{if errors.name "style-error"}}" }}

It caused building error.

the errors.name here is property from controller.

I reckon that it is the nested double curly braces causing the syntax error, but don't know how to achieve this conditional class declaration.

glenlivet1986
  • 260
  • 3
  • 12

2 Answers2

15

You can nest helpers using parenthesis:

{{input class=(if errors.name "style-error")}}

You should use this instead of the xxxBinding="..." syntax


You can use the concat helper to conditionally add multiple classes:

Conditionally add static + dynamic class:

{{input class=(if errors.name (concat "static-class " dynamicClass))}}

Conditionally add two dynamic classes:

{{input class=(if errors.name (concat dynamicClass1 " " dynamicClass2))}}

Add one class if the condition is true, another if it's false:

{{input class=(if errors.name "style-error" "style-success")}}

Add a class only when the condition is false:

{{input class=(unless errors.name "style-success")}}

Two conditions:

{{input class=(concat (if errors.name "name-error") " " (if errors.date "date-error"))}}

For more complex boolean arithmetic (e.g. and/or/not, equality and comparisons) you can use ember-truth-helpers

dwickern
  • 3,519
  • 1
  • 14
  • 21
  • Awesome! so what if there are both static class and dynamic class, or two dynamic classes based on different conditions. – glenlivet1986 Nov 10 '15 at 06:14
  • very helpful answer. however, this complexity is one of drawbacks in Ember.js. – glenlivet1986 Nov 10 '15 at 06:49
  • Indeed, but these are some extreme examples. Instead of complex logic in the template, you should add a property to your component/controller – dwickern Nov 10 '15 at 16:37
3

Since input is an Ember helper here and not an HTML element use classBinding -

{{input classBinding="errors.name:style-error"}}

classBinding takes a space-separated list of arguments in the format of <condition>:<class if true>:<class if false>. So in this case style-error will be applied when errors.name evaluates to true (ie the key exists on the hash).

Its the same syntax as bind-attr. Also, :<class> works, and <condition>::<class if false>. See the docs here.

Note that classBinding is currently supported (discussion here), but it is expected to be deprecated sometime before 3.0 (with appropriate deprecation warnings) with the introduction of angle bracket components.

andorov
  • 4,197
  • 3
  • 39
  • 52
  • this is not working. `errors.name` here is a property in controller. – glenlivet1986 Nov 10 '15 at 02:19
  • See my edit. If it's still not working, what version of ember are you using? – andorov Nov 10 '15 at 03:37
  • v1.13.0 with Ember-cli. it works. thanks! where does the attribute be documented? cannot find any documentation about this. Also, if this is about to be deprecated, then what is the replacement strategy? – glenlivet1986 Nov 10 '15 at 04:03