In this article, I’m going to explain css binding for observable collection using knockout js and have a requirement for show/ hide div using css binding.
Table of Contents
- Code sample for data-bind in view.
- Code sample for ViewModel.
In the 1st
step: Writing the code
for “View”
<div data-bind="style: {display: showHideDiv() ? 'block' : 'none' }">
<!— Need to display your view want to show or hide -->
</div>
In the 2nd
step: Writing the code for “View model”
<script type="text/javascript">
function myViewModel() {
this.showHideDiv = ko.observable(true);
}
ko.applyBindings(new myViewModel());
</script>
In the above, the myViewModel(){}
have showHideDiv() observable is true that means the div is display by default otherwise hide.
If you need to hide to div, that time we can write to( this.showHideDiv = ko.observable(false)) i.e.
<script type="text/javascript">
function myViewModel() {
this.showHideDiv = ko.observable(false);
}
ko.applyBindings(new myViewModel());
</script>