Introduction

In this post we will see an example on cascading or dependent dropdown using Angular 8. When you have a requirement for selecting dropdown values based on another dropdown values then you need to create such cascading dropdown. For example, in your application you need to select city based on state or country then you need to create such dependent dropdown.

Here we will create some dummy dataset for country, state and city and we will show in the dropdown with select/option tags.

The first dropdown will contain country names, the second dropdown will show state names based on the country name and finally third dropdown will show city names based on the state name from the second dropdown.

Prerequisites

Node v12.9.1, Npm 6.10.2, Angular 8, Windows 10 64 bit

Example

We will show you an example on cascading or dependent dropdown with select options for Country -> State -> City. So when you select Country you will corresponding States and when you select State you will get corresponding Cities.

Final Results

You will see the below page on the browser for the home page, where you will see three cascading dropdown as shown in the below image:

cascading or dependent dropdown using angular

Selecting dropdown’s value you will get another dropdown populated:

cascading or dependent dropdown using angular

Creating Angular Application

We will create and build angular application to create cascading dropdown.

The Angular app name is angular-dependent-dropdown.

Once your new application runs successfully, you need to edit the file app.component.ts to write functions which will be called on change event so that other dropdown’s value will get auto-populated.

import { OnInit, Component } from '@angular/core';
import { Title } from '@angular/platform-browser';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
	
	constructor(private title: Title) {}

	ngOnInit() {
		this.title.setTitle('Angular Cascading or Dependent Dropdown');
	}
	
	selectedCountry: String = "--Choose Country--";
  
	Countries: Array<any> = [
		{ name: 'Germany', states: [ {name: 'A', cities: ['Duesseldorf', 'Leinfelden-Echterdingen', 'Eschborn']} ] },
		{ name: 'Spain', states: [ {name: 'B', cities: ['Barcelona']} ] },
		{ name: 'USA', states: [ {name: 'C', cities: ['Downers Grove']} ] },
		{ name: 'Mexico', states: [ {name: 'D', cities: ['Puebla']} ] },
		{ name: 'India', states: [ {name: 'E', cities: ['Delhi', 'Kolkata', 'Mumbai', 'Bangalore']} ] },
	];
  
	states: Array<any>;

	cities: Array<any>;
	
	changeCountry(country) {
		this.states = this.Countries.find(cntry => cntry.name == country).states;
	}

	changeState(state) {
		this.cities = this.Countries.find(cntry => cntry.name == this.selectedCountry).states.find(stat => stat.name == state).cities;
	}
}

We implement OnInit interface – a lifecycle hook that is called after Angular has initialized all data-bound properties of a directive and we need to define an ngOnInit() method to handle any additional initialization tasks – to set the title of the page otherwise you will see the default title (app’s name) of the page. Alternatively you can also set page title in the index.html file under src directory but this will set title for the whole application.

We have class level variable selectedCountry to keep track of which country is selected.

We define a list of countries with states and corresponding cities. These values are not completely real values, so you need to work on real values to show in the dropdown.

We have declared two variables states and cities and these variables will be populated dynamically.

We define two methods changeCountry() and changeState() to show corresponding states and cities respectively.

You need to add FormsModule to work with the HTML form. Import and FormsModule in the app.module.ts file.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
	FormsModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

You can edit the file app.component.html and write below code into the file to build the cascading dropdown using select option tags.

<style>
  .content {
    display: flex;
    margin: 32px auto;
    padding: 0 16px;
    max-width: 960px;
    flex-direction: column;
    align-items: center;
  }

  .card-container {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    margin-top: 16px;
  }
</style>

<div class="content">
	<h2>Cascading or Dependent Dropdown using Angular 8</h2>
	
	<div class="card-container">
		<label>Country</label>
		<select placeholder="Country" [(ngModel)]="selectedCountry" (change)="changeCountry($event.target.value)">
			<option>--Choose Country--</option>
			<option *ngFor="let country of Countries">{{country.name}}</option>
		</select>
	</div>

	<div class="card-container">
		<label>State</label>
		<select placeholder="State" (change)="changeState($event.target.value)">
			<option>--Choose State--</option>
			<option *ngFor="let state of states">{{state.name}}</option>
		</select>
	</div>
	
	<div class="card-container">
		<label>City</label>
		<select placeholder="City">
			<option>--Choose City--</option>
			<option *ngFor="let city of cities">{{city}}</option>
		</select>
	</div>
</div>

<router-outlet></router-outlet>

In the above file we have done binding of selectedCountry with ngModel to track the variable’s state with values.

We are tracking dropdown’s value change using change event and populating other dropdown.

We iterate list of countries or states or cities using ngFor loop.

Source Code

You can download source code.

Thanks for reading.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *