javascriptjsonknockout.jssingle-page-applicationjavascript-databinding

Creating new line using knockout text


I am creating SPA. I am using knockout and observable array to iterate json array. Sometimes i've got br tag inside text, and using data-bind="text: myVar" I would like to brek line. Problem is, br tags wont work, because i can see <br /> except new line. My question is: how can I force knockout data-bind to create new line using this br tags from json data?. I was trying to use "white-space: pre-wrap", but didn't work.


Solution

  • You just need to bind using html: instead of text: and it will process the <br />.

    Run the below snippet:

    var viewModel = {
      myVal: ko.observable('First Line <br />Second Line <br />Third Line')
    };
    
    ko.applyBindings(viewModel);
    * {
      font-family: Arial;
      }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
    <h2>Text Binding:</h2>
    <span data-bind="text: myVal"></span>
    <h2>HTML Binding:</h2>
    <span data-bind="html: myVal"></span>