KnockoutJS Hide HTML shell if condition is met

I created a gridview component, and if the user provides the header as a parameter, I want it to be wrapped in a bootstrap panel. I really don't want to duplicate my markup, so I tried to use control syntax without a container to prevent the panel HTML panel from being added to the DOM.

Here is my attempt:

<!-- ko if: $root.title-->
<div class="panel panel-default">
    <div class="panel-heading">
        <h3 class="panel-title" data-bind="text: $root.title"></h3>
    </div>
    <div class="panel-body">
<!-- /ko -->
        <table class="table table-striped">
            <thead>
            <tr data-bind="foreach: columns">
                <th data-bind="text: headerText"></th>
            </tr>
            </thead>
            <tbody data-bind="foreach: itemsOnCurrentPage">
            <tr data-bind="foreach: $parent.columns">
                <td data-bind="html: typeof rowText == 'function' ? rowText($parent) : $parent[rowText]"></td>
            </tr>
            </tbody>
        </table>
        <nav data-bind="visible: maxPageIndex() > 0">
            <ul class="pagination">
                <li data-bind="click: previousPage">
                    <a href="#" aria-label="Previous">
                        <span aria-hidden="true">&laquo;</span>
                    </a>
                </li>
                <!-- ko foreach: ko.utils.range(0, maxPageIndex) -->
                <li data-bind="css: { active: $data == $parent.currentPageIndex }, click: function(){$parent.updateCurrentPageIndex($data)}">
                    <a href="#" data-bind="text: $data + 1"></a>
                </li>
                <!-- /ko -->
                <li data-bind="click: nextPage">
                    <a href="#" aria-label="Next">
                        <span aria-hidden="true">&raquo;</span>
                    </a>
                </li>
            </ul>
        </nav>
 <!-- ko if: $root.title -->
    </div>
</div>
<!-- /ko -->

However, the result is incorrect. If I invert the condition on ifnot: $parent.title, it is hiding correctly.

Result with if: $parent.title Result

Any suggestions?

+4
source share
1 answer

, , HTML. , div, , , , .

, , CSS panel panel-default, typeof $root.title === 'undefined'

<div class="panel panel-default" data-bind="css:{'panel panel-default': typeof $root.title !== 'undefined'}">
    <div class="panel-heading">
        <h3 class="panel-title" data-bind="text: $root.title"></h3>
    </div>
    <div class="panel-body" data-bind="css:{'panel-body': typeof $root.title !== 'undefined'}">

, , .

0

Source: https://habr.com/ru/post/1624271/


All Articles