knockout.jsknockout-components

Knockout 3.2: can components / custom elements contain child content?


Can I create non-empty Knockout components that use the child markup within them?

An example would be a component for displaying a modal dialog, such as:

<modal-dialog>
  <h1>Are you sure you want to quit?</h1>
  <p>All unsaved changes will be lost</p>
</modal-dialog>

Which together with the component template:

<div class="modal">
  <header>
    <button>X</button>
  </header>

  <section>
    <!-- component child content somehow goes here -->
  </section>

  <footer>
    <button>Cancel</button>
    <button>Confirm</button>
  </footer>
</div>

Outputs:

<div class="modal">
  <header>
    <button>X</button>
  </header>

  <section>
    <h1>Are you sure you want to quit?</h1>
    <p>All unsaved changes will be lost</p>
  </section>

  <footer>
    <button>Cancel</button>
    <button>Confirm</button>
  </footer>
</div>

Solution

  • It's impossible in 3.2, however it would be possible in next version, see this commit and this test.

    For now to you have to pass parameters to component via params property Define your component to expect content parameter:

    ko.components.register('modal-dialog', {
        viewModel: function(params) {
            this.content = ko.observable(params && params.content || '');
        },
        template:
            '<div class="modal">' +
                '<header>' +
                    '<button>X</button>' +
                '</header>' +
                '<section data-bind="html: content" />' +
                '<footer>' +
                    '<button>Cancel</button>' +
                    '<button>Confirm</button>' +
                '</footer>' +
            '</div>'
    });
    

    Pass content parameter via params property

    <modal-dialog params='content: "<h1>Are you sure you want to quit?</h1> <p>All unsaved changes will be lost</p>"'>
    </modal-dialog>
    

    See fiddle

    In new version you can use $componentTemplateNodes

    ko.components.register('modal-dialog', {
        template:
            '<div class="modal">' +
                '<header>' +
                    '<button>X</button>' +
                '</header>' +
                '<section data-bind="template: { nodes: $componentTemplateNodes }" />' +
                '<footer>' +
                    '<button>Cancel</button>' +
                    '<button>Confirm</button>' +
                '</footer>' +
            '</div>'
    });
    

    Usage in parent component:

    <modal-dialog><div>This div is displayed in the <section> element of the modal-dialog</div>
    </modal-dialog>
    

    P.S. You can build last version of knockout manually to use code above.