Is it possible to have nested knockout components in javascript

I need something like this:

<base-component>
    <sec-component>
    </sec-component>
</base-component>

Can this be achieved with knockout components?

+4
source share
1 answer

Yes. In the documentation, the section "Passing markup to components": http://knockoutjs.com/documentation/component-custom-elements.html#passing-markup-into-components

<!-- This could be in a separate file -->
<template id="my-special-list-template">
    <h3>Here is a special list</h3>

    <ul data-bind="foreach: { data: myItems, as: 'myItem' }">
        <li>
            <h4>Here is another one of my special items</h4>
            <!-- ko template: { nodes: $componentTemplateNodes, data: myItem } --><!-- /ko -->
        </li>
    </ul>
</template>

<my-special-list params="items: someArrayOfPeople">
    <!-- Look, I'm putting markup inside a custom element -->
    The person <em data-bind="text: name"></em>
    is <em data-bind="text: age"></em> years old.
</my-special-list>

The ko templateinside of the element linodes are added.

Therefore, you can also insert another component in the internal markup. For instance:

<!-- This could be in a separate file -->
<template id="my-special-list-template">
    <h3>Here is a special list</h3>

    <ul data-bind="foreach: { data: myItems, as: 'myItem' }">
        <li>
            <h4>Here is another one of my special items</h4>
            <!-- ko template: { nodes: $componentTemplateNodes, data: myItem } --><!-- /ko -->
        </li>
    </ul>
</template>

<template id="my-person-template">
    The person <em data-bind="text: name"></em>
    is <em data-bind="text: age"></em> years old.
</template>

<my-special-list params="items: someArrayOfPeople">
    <my-person></my-person>
</my-special-list>
+7
source

All Articles