Search code examples
knockout.jscarriage-returnparagraph

Knockout.js carraige return in paragraph text


Using knockout.js, how do I include a carriage return in the text that is bound to the text attribute of a paragraph <p> element.

In my ViewModel I generated a string of text that is bound to the <p> in the View. I want to include carriage returns in the string which the browser displays with the line breaks.

Including <br /> or Environment.NewLine in the string does not seem to work.


Solution

  • You can use the html binding.

    JS:

    function AppViewModel() {
        this.firstName = "Bert<br\>Test";
        this.lastName = "Bertington";
    }
    
    // Activates knockout.js
    ko.applyBindings(new AppViewModel());
    

    View :

    <p>First name: <strong data-bind="html: firstName">todo</strong></p>
    <p>Last name: <strong>todo</strong></p>
    

    See fiddle