How to append knockout component dynamically in the DOM?

2,659 views
Skip to first unread message

nanj...@gmail.com

unread,
Jun 3, 2016, 8:11:36 AM6/3/16
to KnockoutJS
Hi experts,

Is there a way for knockout to append KO component dynamically in the DOM.
For example,
<div id="parent">
     <div data-bind="foreach: components">
              <div data-bind="component: {name: NAME, params: $data}"></div>
     </div>
</div>

The viewModel "parentViewModel" is binded to $("#parent").  I want to add a new component dynamically in parent, like:

var newComponent = $("#parent").append(' <div data-bind="component: {name: NEW_NAME, params: newParams}"></div>');

However the datas in the new component does not load. What is wrong in above code? Or is there another way to append new component?

Thanks

noirabys

unread,
Jun 9, 2016, 4:53:57 AM6/9/16
to KnockoutJS
Hi,
don't manipulate the dom yourself. work on the model and let knockout do the rest .

any node added after applyBindings call may not be managed by knockout.

how did you define the components ... or are they loaded dynamically ?

best regards,
  noirabys

Aries Dane

unread,
Jun 13, 2016, 10:22:37 AM6/13/16
to KnockoutJS
If you want to manually inject components as raw HTML into you're page using jQuery, then you'll need to call ko.applyBindings() after the HTML has been added.

NOTE: Knockout will throw an error if you call applyBindings() on the same DOM element more than once.

Thus, don't do ko.applyBindings(model, $("#parent")[0]) if you plan to inject different HTML at a later time. Instead, use ko.applyBindings(model, $("#parent > :first")[0]). Remember, ko.applyBindings(model, element) expects a single element, so if your #parent will contain multiple children then wrap them inside a <div> before adding them to the #parent.

Alternatively, manage the list of child components in your model rather than injecting raw HTML.
Reply all
Reply to author
Forward
0 new messages