Knockout Dependent Observables Example

So many times we have a scenario where we want to populate a dropdown based on selection of another dropdown. For example, selection of country and states or for selection of cars based on make and models. In this blog, we will see how we can use knockout's dependent observable to accomplish this.

Let's take a look at the code first-

Here, we have two selects, the first one is for country selection and the other one is for state selection. We want the state list to be populated based on country selection.
The first select is bound to countries observable array. The second select is bound to selectedStates which is a dependent observable array. Whenever we select a country the value gets stored in selectedCountry. The dependent observable selectedStates is evaluated based on this value. We use the knockout's array filter helper method to select the states which have the same country key as the selectedCountry.