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

Is it possible to create non-empty knockout components that use child markup inside them?

An example is a component for displaying a modal dialog, for example:

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

What comes 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> 
+3
source share
1 answer

This is not possible in 3.2, however it is possible in the next version, see this commit and this test .

Now you need to pass the parameters to the component via the params property Define your component to wait for the 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>' }); 

Skip content parameter through 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 the 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>' }); 

PS You can manually create the latest knockout to use the code above.

+6
source

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


All Articles