Skip to main content Skip to footer

Link the itemSources of Two Different Components in Angular

Background:

There may be times when you need to populate the values of one ComboBox based on the selection of another ComboBox. This is possible to implement using the textChanged event to update the second ComboBox when the first gets changed by a user.

Steps to Complete:

1. Create two ComboBoxes, one with an itemsSource and one without

2. Prevent the selection of a value in the first ComboBox when the page loads

3. Couple a method with the textChanged event of the main ComboBox to update the second ComboBox

Getting Started

Create two ComboBoxes, one with an itemsSource and one without

We only assign an itemsSource to the first ComboBox. The second one doesn't get an itemsSource assigned because its going to be dependent on the selection of the first. A mtehod also needs assigned to the textChanged event.

<wj-combo-box #firstCombo [itemsSource]="cv" (textChanged)="updateSecondCombo()"></wj-combo-box>
<wj-combo-box #secondCombo></wj-combo-box>

Prevent the selection of a value in the first ComboBox when the page loads

In order to prevent anything from loading automatically, we're going to prevent the first ComboBox from having a default value when it loads. This will prevent the second ComboBox from trying to update itself when a user hasn't selected anything yet. To do this, we'll set the currentItem property in the ComboBox.

cv = new wjcCore.ColelctionView(this.categories, { currentItem: null });

Couple a method with the textChanged event of the main ComboBox to update the second ComboBox

Next, the updateSecondCombo() method needs to handle updating the second ComboBox when a change is made to the first. TextChanged will fire whenever the text in the ComboBox changes, like when the user clicks a different option. What then happens is, depending on the text in the first ComboBox, we decide what array to push onto the itemsSource of the second.

updateSecondCombo() {
    if(this.firstCombo.text === 'Food') {
        this.secondCombo.itemsSource = new wjcCore.CollectionView(this.food);
    } else if(this.firstCombo.text === 'Cars') {
        this.secondCombo.itemsSource = new wjcCore.CollectionView(this.cars);
    } else {
        this.secondCombo.itemsSource = new wjcCore.CollectionView(this.places);
    }
}

This will insert the list into the itemsSource, as well as replace the itemsSource if you go from one selection in the first ComboBox to a different item in the list.

You can find a live sample of this project here: https://stackblitz.com/edit/wijmo-knowledgebase-angular-input-link-control-itemssources

Joel Parks