Mujahid
Mujahid

Reputation: 1237

Knockout data-bind if else condition

In my current project, I have a knockout binding where the layout height should be applied according to the value received as true or false. Following is my binding code

data-bind="style: {height: showOld ? '392px' : '275px'}"

The showOld gives either true or false correctly, but, regardless what it returns, it always take 392px. If the showOld gives true then 392px should return else 275px should return. Any help to fix this issue is highly appreciate.

Thanks

Upvotes: 0

Views: 11017

Answers (1)

nemesv
nemesv

Reputation: 139798

If your showOld is ko.observable then you need to write showOld() (because ko.observable is a function) to get its value in your expression:

data-bind="style: {height: showOld() ? '392px' : '275px'}"

From the documentation:

To read the observable’s current value, just call the observable with no parameters.

To write a new value to the observable, call the observable and pass the new value as a parameter. For example, calling myViewModel.personName('Mary') will change the name value to 'Mary'.

Upvotes: 4

Related Questions