Skip to content

Knockout: Render child component with passed data

In my Magento 2 knockout component i have the case where i loop through some filters() object and want to render each filter as a child template. Therefore i want to pass the $data from the foreach to the child and use it.

The $data variable contains an object like this:

{
    label: 'Label'
    options: {}
}

If i echo the $data in the parent component with a text binding and JSON.stringify it contains the correct data.

What i tried:

<!-- ko foreach: filter() -->
    <!-- ko with: $parent.getChild('search_filter') -->
        <!-- ko template: { name: getTemplate(), data: $data, as: 'searchFilter' } --><!-- /ko -->
    <!-- /ko -->
<!-- /ko -->

In my child component search-filter.js component i have:

define([
    'jquery',
    'ko',
    'uiComponent',
], function ($, ko, Component) {
    'use strict';

    return Component.extend({
        defaults: {
            searchFilter: null
        },

        initialize: function () {
            this._super();
            console.log(this.searchFilter);
        }
    });
});

With this, the console log always shows null.

I also tried this, without success:

<!-- ko template: { name: getTemplate(), templateOptions: {myvar: $data} } --><!-- /ko -->

My XML:

<item name="filter" xsi:type="array">
    <item name="component" xsi:type="string">Module_Namespace/js/view/list/filter</item>
    <item name="config" xsi:type="array">
        <item name="template" xsi:type="string">Module_Namespace/list/filter</item>
    </item>
    <item name="children" xsi:type="array">
        <item name="search_filter" xsi:type="array">
            <item name="component" xsi:type="string">Module_Namespace/js/view/list/search-filter</item>
            <item name="displayArea" xsi:type="string">search_filter</item>
            <item name="config" xsi:type="array">
                <item name="template" xsi:type="string">Module_Namespace/list/search-filter</item>
            </item>
        </item>
    </item>
</item>

I didn’t find any example in the core or useful documentation.