Introduction:
Cascading dropdowns are a common user interface pattern that allows users to select options from a series of related dropdowns, where the options in one dropdown depend on the selection made in the previous dropdown. Angular provides a powerful and straightforward way to implement cascading dropdowns using reactive forms and event binding. In this blog post, we will walk you through the process of creating cascading dropdowns in Angular, step by step, with practical examples.
If you want to learn more about the Principles and Concepts of Functional Programming, please refer here.
1. What are Cascading Dropdowns?
Cascading dropdowns, also known as dependent dropdowns, are a series of dropdowns where the options in one dropdown are based on the selected value of another dropdown. For example, if you have a Country dropdown, the available options in the State dropdown will change based on the selected country.
2. Setting Up the Angular Project:
Before we begin, make sure you have Angular CLI installed. If not, you can install it globally using the following command:
npm install -g @angular/cli
Now, let’s create a new Angular project using the CLI:
ng new cascading-dropdown-example
cd cascading-dropdown-example
3. Creating the Data Source:
In this example, let’s assume we have two datasets: one for countries and another for states. For simplicity, we’ll create two separate arrays within a shared service to simulate these datasets.
country.service.ts:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class CountryService {
getCountries(): string[] {
return ['USA', 'Canada', 'India'];
}
getStatesByCountry(country: string): string[] {
// Simulating state data based on the selected country
switch (country) {
case 'USA':
return ['New York', 'California', 'Texas'];
case 'Canada':
return ['Ontario', 'British Columbia', 'Quebec'];
case 'India':
return ['Delhi', 'Maharashtra', 'Karnataka'];
default:
return [];
}
}
}
4. Building the Cascading Dropdown Components:
a. Parent Dropdown Component:
Create the parent dropdown component to display the list of countries.
parent-dropdown.component.html:
<select (change)="onCountryChange($event.target.value)">
<option value="">Select Country</option>
<option *ngFor="let country of countries" [value]="country">{{ country }}</option>
</select>
parent-dropdown.component.ts:
import { Component, OnInit } from '@angular/core';
import { CountryService } from '../services/country.service';
@Component({
selector: 'app-parent-dropdown',
templateUrl: './parent-dropdown.component.html',
})
export class ParentDropdownComponent implements OnInit {
countries: string[] = [];
constructor(private countryService: CountryService) {}
ngOnInit() {
this.countries = this.countryService.getCountries();
}
onCountryChange(selectedCountry: string) {
// TODO: Implement the logic to update the child dropdown options based on the selected country.
}
}
b. Child Dropdown Component:
Create the child dropdown component to display the list of states based on the selected country.
child-dropdown.component.html:
<select>
<option value="">Select State</option>
<option *ngFor="let state of states" [value]="state">{{ state }}</option>
</select>
child-dropdown.component.ts:
import { Component, Input } from '@angular/core';
import { CountryService } from '../services/country.service';
@Component({
selector: 'app-child-dropdown',
templateUrl: './child-dropdown.component.html',
})
export class ChildDropdownComponent {
@Input() selectedCountry: string;
states: string[] = [];
constructor(private countryService: CountryService) {}
ngOnChanges() {
this.states = this.countryService.getStatesByCountry(this.selectedCountry);
}
}
5. Implementing the Reactive Form:
To manage the communication between the parent and child dropdown components, we’ll use Angular’s reactive forms. Modify the parent component template as follows:
parent-dropdown.component.html:
<form [formGroup]="formGroup">
<select formControlName="countryControl" (change)="onCountryChange()">
<option value="">Select Country</option>
<option *ngFor="let country of countries" [value]="country">{{ country }}</option>
</select>
</form>
<app-child-dropdown [selectedCountry]="formGroup.get('countryControl').value"></app-child-dropdown>
parent-dropdown.component.ts:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { CountryService } from '../services/country.service';
@Component({
selector: 'app-parent-dropdown',
templateUrl: './parent-dropdown.component.html',
})
export class ParentDropdownComponent implements OnInit {
formGroup: FormGroup;
countries: string[] = [];
constructor(private countryService: CountryService, private formBuilder: FormBuilder) {}
ngOnInit() {
this.countries = this.countryService.getCountries();
this.formGroup = this.formBuilder.group({
countryControl: [''], // Initialize with an empty value
});
}
onCountryChange() {
// No need to do anything here, the child component will automatically update the states based on the selected country.
}
}
6. Adding Event Binding and Updating Child Dropdown:
In the child component, we have already set up the ngOnChanges()
method to update the list of states whenever the selected country changes. Now, let’s bind the onCountryChange()
event in the parent component to update the child component when the user selects a country.
7. Testing and Troubleshooting:
Run your Angular application using the following command:
ng serve
Open your browser and navigate to http://localhost:4200
. You should see the parent dropdown with the countries listed. When you select a country, the child dropdown should automatically update with the states relevant to the selected country.
If you encounter any issues, make sure to check the console for error messages and review your code for any possible mistakes.
8. Conclusion:
In this blog, we have learned how to create cascading dropdowns in Angular using reactive forms and event binding. Cascading dropdowns provide a user-friendly way to handle related data and simplify data selection for users. By following the steps outlined in this guide and understanding the communication between parent and child components, you can easily implement cascading dropdowns in your Angular applications.
Cascading dropdowns are just one example of how Angular can be used to create powerful and interactive user interfaces. As you continue to explore Angular, you will discover many more features and possibilities to enhance your web applications. Happy coding!
Finally, for more such posts, please follow our LinkedIn page- FrontEnd Competency.