Search code examples
javascripthtmlknockout.jsknockout-componentsknockout-templating

How can I add HTML to this Knockout.js Viewmodel variable?


I have a list of steps displayed on the page. Some steps (but not all) will have 1-3 substeps. I was thinking the simplest way of doing this was to just write the HTML manually within each step declaration in the viewmodel.

If you look in the code below, what I want to do is something like:

this.sidebarStepModel1 = new SidebarStepModel();
this.sidebarStepModel1.message("step 2 <ul><li>substep 1</li><li>substep2</li></ul>");

The problem is, HTML written in there is interpreted as a string and not as HTML. How can I make it so that it interprets the HTML as actual HTML?

Fiddle: https://jsfiddle.net/8o31m6rq/2/

HTML:

<ul>
    <sidebar-step params="vm: sidebarStepModel0"></sidebar-step>
    <sidebar-step params="vm: sidebarStepModel1"></sidebar-step>
    <sidebar-step params="vm: sidebarStepModel2"></sidebar-step>
</ul>

JavaScript/Knockout:

//custom element <sidebar-step>
ko.components.register("sidebar-step", {
    synchronous: true,
    viewModel: function (params) {
        this.vm = params.vm;
    },

    template: "<li data-bind='text: vm.message'>vm.onChangeElement</li>"
});

// model
var SidebarStepModel = function () {
    this.message = ko.observable("step description");
};

// viewmodel
var OrderGuideViewModel = function () {

    this.sidebarStepModel0 = new SidebarStepModel();
    this.sidebarStepModel0.message("step 1");

    this.sidebarStepModel1 = new SidebarStepModel();
    this.sidebarStepModel1.message("step 2");

    this.sidebarStepModel2 = new SidebarStepModel();
    this.sidebarStepModel2.message("step 3");
};

ko.applyBindings(new OrderGuideViewModel());

Solution

  • You just need to use the html binding instead of the text binding:

    template: "<li data-bind='html: vm.message'>vm.onChangeElement</li>"
    

    Updated fiddle