I am trying to create a custom component in knockout.js.
HTML
<demo-widget>TEXT NEEDED</demo-widget>
Javascript
ko.components.register('demo-widget', {
template: '<div>New Text</div>'
});
ko.applyBindings();
The component loads fine and everything, but what I now want to do is to be able to get any content that was inside the original custom component tag(example the "TEXT NEEDED" text).
Any idea how I can do this? Hope I explained it clearly enough.
Here is a fiddle: http://jsfiddle.net/WhesleyBarnard/f7bmynp5/5/
This is possible now (as of Knockout 3.3), see the KnockoutJS documentation here: Passing markup into components.
I won't copy the whole text here, but the gist is:
By default, the DOM nodes inside [your component] will be stripped out (without being bound to any viewmodel) and replaced by the component’s output. However, those DOM nodes aren’t lost: they are remembered, and are supplied to the component in two ways:
- As an array,
$componentTemplateNodes
, available to any binding expression in the component’s template (i.e., as a binding context property). Usually this is the most convenient way to use the supplied markup. See the example below.- As an array,
componentInfo.templateNodes
, passed to itscreateViewModel
functionThe component can then choose to use the supplied DOM nodes as part of its output however it wishes, such as by using
template: { nodes: $componentTemplateNodes }
on any element in the component’s template.
Related SO question: Knockout 3.2: can components / custom elements contain child content?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With