29

Is this possible to have if-else statement when using knockout container less statements? I mean Something like:

<!-- ko else -->
Anonymous
  • 11,748
  • 6
  • 35
  • 57
xpollcon
  • 525
  • 1
  • 6
  • 9
  • there is no ko else. but you can check this out http://stackoverflow.com/questions/11553999/knockout-js-if-else-bindings – huocp Apr 01 '14 at 01:17
  • Checkout this blog : https://www.rohanhapani.com/how-to-use-if-else-in-knockout-js-in-magento-2/ – Rohan Hapani Jun 05 '20 at 06:30

3 Answers3

71

As mentioned, there isn't an else, but it's common to combine ko if and ko ifnot using the same flag.

<!-- ko if: myFlag -->
    ...some stuff for the true case
<!-- /ko -->
<!-- ko ifnot: myFlag -->
    ...some stuff for the else (false) case
<!-- /ko -->
Joseph Gabriel
  • 8,339
  • 3
  • 39
  • 53
3

Unfortunately there is no <!-- ko else -->. you will need to use two <!-- ko if: something-is-true --> statements or use templates to achieve the same thing as @huocp mentioned with the link to Knockout JS If-Else bindings

Community
  • 1
  • 1
Nathan Fisher
  • 7,961
  • 3
  • 47
  • 68
1

One solution already mentioned in above answers using ifnot.But you can use same this way

<!-- ko if: myFlag -->
    ..if statement work here
<!-- /ko -->
<!-- ko if: !(myFlag) -->
    ..else statement work here
<!-- /ko -->
Usman Shah
  • 51
  • 2