Angular: How to Load Cascading List in Single Dropdown

Load-Cascading-List-in-Single-Dropdown-Angular
Dhara Tank
18-Dec-2020
Reading Time: 5 minutes

In this tutorial article, we’ll learn how you can load cascading list in single dropdown using Angular 10.

Prerequisites:

  1. Prior knowledge of TypeScript.
  2. Prior knowledge of JavaScript.
  3. Visual studio code.
  4. A development machine with Node 11.3 + & NPM 9.1.7+ installed.

Step-by-Step Tutorial of Loading Cascading List in Dropdown using Angular 10

Step 1: Installing Angular CLI

First step, where we’ll have to install latest version of Angular CLI.

$ npm install -g @angular/cli

Step 2: Creating your Angular 10 Project

  • In this second step, we will use Angular CLI to start our Angular Project
  • Go to CMD or Terminal and use this command:
$ ng new dynamicDemo
  • This CLI will ask you “whether you would like to add Angular routing?” Say Yes.
  • It will ask “which stylesheet format you would like to use?”. Choose CSS.
  • Now your project is ready Angular CLI will generate required files and folders along with NPM packages and routing too.
  • Now open your project in Visual studio code and go to your root folder and run the local development server using below command:
$ npm start
Angular CLI Installation CMD Image
Angular CLI Installation CMD Image

Now run localhost:4200/ in your browser.

Step 3: Add Interface / Class model

  • Here we are using interface. So, create interface.ts file
  • Create interface for
    • Country,
    • State,
    • City
    • Selected Values
export interface ICountry {
    id: number,
    name: string
}

export interface IState {
    id: number,
    name: string,
    countryId: number
}

export interface ICity {
    id: number,
    name: string,
    stateId: number
}

export interface ISelectVal {
    text: string;
    type: string;
}

Step 4: Create Service

Create service for Get data from  API /  JSON string.

Create Services Angular: How to Load Cascading List in Single Dropdown
getCountries() {
    return [
      { id: 1, name: "India" },
      { id: 2, name: "Australia" },
      { id: 3, name: "USA" },
    ]
}

getStates() {
    return [
      { id: 1, countryId: 1, name: 'Gujarat' },
      { id: 2, countryId: 1, name: 'Maharashtra' },
      { id: 4, countryId: 1, name: 'Rajasthan' },


      { id: 5, countryId: 2, name: 'South Australia' },
      { id: 6, countryId: 2, name: 'Victoria' },

      { id: 8, countryId: 3, name: 'Texas' },
      { id: 9, countryId: 3, name: 'California' },
      { id: 10, countryId: 3, name: 'Florida' },

    ];
}

Step 4: Create Component

Use this command

$ ng g c test

Step 5 : Declare page variables, import service & interface / class

Add below code snippet into test.component.ts file

import { Component, OnInit } from '@angular/core';
import { ICountry, IState, ICity, ISelectVal } from '../interface';
import { CommonService } from '../common.service'

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {

  //Get all List
  
  countryList: ICountry[] = [];
  stateListAll: IState[] = [];
  cityListAll: ICity[] = [];
ngOnInit(): void {
    this.GetAllData();
}
GetAllData() {
    this.countryList = this.commonService.getCountries();
    this.stateListAll = this.commonService.getStates();
    this.cityListAll = this.commonService.getCity();
}

Step 6: Set HTML and bind the default page values

  • Here we are taking example for country, state & city. So, country is default page values.
  • Add below code snippet in test.component.html file
<!-- Selected values Section -->
<div class="itms">
    <div class="chip" *ngFor="let val of selectedValues;let idx = index">
        <span>{{val.text}}</span>
        <span (click)="deleteSelects(val,val.type)" class="closebtn">&#10006;</span>
    </div>
</div>

<!-- Different dropdown values -->
<!-- country -->
<div class="dropdown-content" *ngIf="isCountrySelect">
    <div class="plchld">Select Country</div>
    <div *ngFor="let c of countryList" (click)="onSelect(c,typeCountry)">
        <img src="../../assets/images/{{c.name}}.png" class="img" />
        {{ c.name }} </div>
</div>

State will be displayed as per the country selection & city will be displayed as per the state selection.

<!-- Selected values Section -->
<div class="itms">
    <div class="chip" *ngFor="let val of selectedValues;let idx = index">
        <span>{{val.text}}</span>
        <span (click)="deleteSelects(val,val.type)" class="closebtn">&#10006;</span>
    </div>
</div>

<!-- Different dropdown values -->
<!-- country -->
<div class="dropdown-content" *ngIf="isCountrySelect">
    <div class="plchld">Select Country</div>
    <div *ngFor="let c of countryList" (click)="onSelect(c,typeCountry)">
        <img src="../../assets/images/{{c.name}}.png" class="img" />
        {{ c.name }} </div>
</div>

<!-- State -->
<div class="dropdown-content" *ngIf="isStateSelect">
    <div class="plchld">Select State</div>
    <div *ngFor="let s of stateList" (click)="onSelect(s,typeState)">{{ s.name }}</div>
</div>

<!-- City -->
<div class="dropdown-content" *ngIf="isCitySelect">
    <div class="plchld">Select City</div>
    <div *ngFor="let ct of cityList" (click)="onSelect(ct,typeCity)">{{ ct.name }}</div>
</div>

Step 7: Create a method on select the value

  • Declare the variables for the show / hide the dropdown values
  • Declare types variable for map the types / selected values
selectedValues: ISelectVal[] = [];
selectedVal: ISelectVal = <ISelectVal>{}; // set all selected values

  // for show / hide 
  isCountrySelect: boolean = true; 
  isStateSelect: boolean = false;
  isCitySelect: boolean = false;

  //Types
  typeCity: string = "City";
  typeState: string = "State";
  typeCountry: string = "Country";

Here “onSelect(c,typeCountry)” will be call on click.

  • On select country,
    • Country dropdown will be hide & state dropdown will be display, set the value in “this.selectedValues”
    • Same as when state will be selected
    • State dropdown will be hide and display  city dropdown.
onSelect(val, selectType) {

    this.selectedVal = <ISelectVal>{};

    this.selectedVal.text = val.name;
    if (selectType == this.typeCountry) {
      this.stateList = this.stateListAll.filter(f => f.countryId == val.id); // can make DB call
      this.isCountrySelect = false;
      this.isStateSelect = true;
      this.selectedVal.type = this.typeCountry;
    }
    else if (selectType == this.typeState) {
      this.cityList = this.cityListAll.filter(f => f.stateId == val.id); // can make DB call
      this.isStateSelect = false;
      this.isCitySelect = true;
      this.selectedVal.type = this.typeState;
    }
    else if (selectType == this.typeCity) {
      this.isCitySelect = false;
      this.selectedVal.type = this.typeCity;
    }
    this.selectedValues.push(this.selectedVal);
  }

Load Component in app.component

Load Component in app component Angular: How to Load Cascading List in Single Dropdown

Step 8: On Delete the Values

Here “deleteSelects(val,val.type)” will be call on click for delete.

Delete List Options Dynamic Angular: How to Load Cascading List in Single Dropdown
<!-- Selected values Section -->
<div class="itms">
    <div class="chip" *ngFor="let val of selectedValues;let idx = index">
        <span>{{val.text}}</span>
        <span (click)="deleteSelects(val,val.type)" class="closebtn">&#10006;</span>
    </div>
</div>
  • On Delete selected City, city dropdown will be display
    • Same as on delete country, country, state and city will be deleted and country dropdown will be display.
deleteSelects(val, selectType) {

    if (selectType == this.typeCountry) {
      this.isStateSelect = false;
      this.isCitySelect = false;
      this.isCountrySelect = true;
    }
    else if (selectType == this.typeState) {
      this.isCitySelect = false;
      this.isStateSelect = true;

    }
    else if (selectType == this.typeCity) {
      this.isCitySelect = true;
    }

    // remove data from selected list
    let idx = this.selectedValues.findIndex(f => f.type == selectType);
    this.selectedValues.map((cm, i) => {
      if (i >= idx) {
        this.selectedValues.splice(i);
      }
      }
    });
}

Over To You!

Looking for a Sample Source Code? Here you go: GITHUB.

That’s it for now. Today you have learn how to load multiple dynamic content in one Page using Angular 8. If you have queries about tutorial, please ask our angular developers via GitHub Profile.

Related Resources:

  1. Angular: Create Dynamic Form with Controls & Validation
  2. N Level FormArray With Reactive Form Validation In Angular