Dynamic component loading
HTML
<script src="http://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-debug.js"></script>
Here's a widget, declared inline:
<like-widget></like-widget>
<button id='btnAdd'>Add a new widget to the grey box:</button>
<br/><br/>
<div id='addZone' class="well">
Widgets will be appended here
</div>
<p>When you run this code, the widget custom element is indeed added to the box (see source) but the widget's template is not bound, so nothing appears. How do I get it to bind/appear?</p>
JavaScript
ko.components.register('like-widget', {
template: '<div class="alert alert-info">This is the widget</div>',
viewModel: {
createViewModel: (params, componentInfo) => {
console.log(params);
}
}
});
ko.applyBindings()
$('#btnAdd').on('click', function() {
let $newWidget = $('<like-widget>');
let $params = {
test: "bladiblabla"
};
$newWidget.attr('params', JSON.stringify($params));
$('#addZone').append($newWidget);
ko.applyBindings({},$newWidget[0]);
});