Same as text binding in knockout html binding works although it can render HTML elements too with data into it.
Secret of working : It uses javascript innerHTML function to bind html markup.
Let’s look at example of it.
Simple example:
We have stockMessage as knockout observable with initial value italic HTML element “In stock” which changes later to out of stock with bold element.
1 2 3 4 5 6 7 8 |
The item is <span data-bind="html: stockMessage"></span>. <script type="text/javascript"> var viewModel = { stockMessage: ko.observable("<i>In Stock</i>") }; viewModel.stockMessage('<b>Out of stock</b>'); ko.applyBindings(viewModel); </script> |
Another Example with condition of quantity:
If item quantity is less than 10 we displays out of stock message in bold and if not than in stock message in italic.
1 2 3 4 5 6 7 8 |
The item is <span data-bind="html: qty() < 10 ? '<b>Out of Stock</b>' : '<i>In Stock</i>' "></span>. <script type="text/javascript"> var viewModel = { qty: ko.observable() }; viewModel.qty(5); ko.applyBindings(viewModel); </script> |
We have bind html markup elements using knockout.