How can I make conditional binding in knockout.js ?

How can I make conditional binding in knockout.js ?

Asked on December 24, 2018 in knockout js.
Add Comment


  • 2 Answer(s)

        For making the conditional binding , Try this method :

    function viewModel() {
        this.itemSelected = ko.observable(true);
    }
    ko.applyBindings(new viewModel());​
    

        After the element itemSelected Including the  () will give the current value of the observable which is used in the   ternary operator :

    <div data-bind="attr: { class: itemSelected() ? 'selected' : 'unselected' }"></div>
    

    Answered on December 24, 2018.
    Add Comment

        For conditional binding, Use both the id attributes and css class. This one will not work if css is not mentioned first.

    <div class="panel-collapse collapse" data-bind="css:{in:$index()==0}, attr: { id:'collapse'+$index()} ">
    ...
    ...
    ...
    </div>
    

     

    Answered on December 24, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.