'Knockout JS - Update view visibility when observable changes value

So I was trying to update an span tag visibility when a value changes, but noticed that using if: and directly using the compare operator there doesn't work when the value changes. For example:

<span data-bind="if: firstName === 'Bert'">Hello</span>

So if we have initially something else in the firstName observable it will not be visible. Theorically if we change the value to Bert (maybe using a text input) or a function that changes the value it should show the Hello span, but it isn't working.



Solution 1:[1]

To update the HTML component using the if statement, we should use a function in the JS and call the function like below.

In the JS (inside the view model):

this.showSpan = function() {
    return this.firstName() === 'Bert'
}

And in the HTML:

<span data-bind="if: showSpan()">Hello</span>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1