How to cascade the dropdowns in Angular 2+



In this tutorial, you will learn about cascading dropdown in the Angular 2+ version, this is one of the major things used while creating the form in the Angular such as registration forms, etc.

Create reusable service to perform HTTP operations

Prepare the generic method in the Angular Service for handling the HTTP requests such as GET, POST, PUT, DELETE

  import { Injectable } from '@angular/core';
  import { HttpClient, HttpHeaders } from '@angular/common/http';
  import { Observable } from 'rxjs';
  import { map } from 'rxjs/operators';

  @Injectable({
    providedIn: 'root'
  })
  export class ApiHandlerService {
    constructor(private http: HttpClient) { }

    getApiRequest(url: string): Observable<any[]> {
      const headerDict = {
        'Content-Type': 'application/json',
        Authorization: 'Basic XXXXX'
      };

      const requestOptions = {
        headers: new HttpHeaders(headerDict)
      };

      return this.http.get(url, requestOptions).pipe(
        map((applicants: any[]) => {
          return applicants;
        })
      );
    }
  }

Inject the above service in the component and get details required for the dropdown from the HTTP As most widely used dependent dropdown would be to select Country, State, and City which are dependent on each other  

import { Component, OnInit } from '@angular/core';
import { ApiHandlerService } from 'src/app/services/api-handler.service';
import { environment } from 'src/environments/environment';

@Component({
	selector: 'app-angular-dependent-dropdown',
	templateUrl: './angular-dependent-dropdown.component.html',
	styleUrls: ['./angular-dependent-dropdown.component.scss']
})
export class AngularDependentDropdownComponent implements OnInit {
	countryArray: any = [];
	stateArray: any = [];
	citiesArray: any = [];
	constructor(private apiHandler: ApiHandlerService) {}

	ngOnInit() {
		this.countryArray = [];
		this.apiHandler.getApiRequest(environment.getCounties).subscribe((data) => {
			data.forEach((item) => {
				this.countryArray.push(item.country_name);
			});
		});
	}

	getStateByCountry(country: string) {
		this.stateArray = [];
		this.apiHandler.getApiRequest(environment.getStates + country).subscribe((data) => {
			data.forEach((item) => {
				this.stateArray.push(item.state_name);
			});
		});
	}

	getCityByState(state: string) {
		this.citiesArray = [];
		this.apiHandler.getApiRequest(environment.getCity + state).subscribe((data) => {
			data.forEach((item) => {
				this.citiesArray.push(item.city_name);
			});
		});
	}
}

Now we can use the dropdowns in the HTML as below, every time user selects the dropdown in the HTML the values in the dependent would be updated

<div class="container">

  <h1 class="mat-display-1">How to cascade dropdowns in Angular 2+</h1>

  <div class="row" [formGroup]="formGroup">
    <div class="col-md-3">
      <mat-form-field>
        <mat-label>Country</mat-label>
        <mat-select placeholder="Country" formControlName="country" (selectionChange)="getStateByCountry($event.value)">
          <mat-option *ngFor="let item of countryArray" value="{{item}}">{{item}}</mat-option>
        </mat-select>
      </mat-form-field>
    </div>
    <div class="col-md-3">
      <mat-form-field>
        <mat-label>State</mat-label>
        <mat-select placeholder="State" formControlName="state" (selectionChange)="getCityByState($event.value)">
          <mat-option *ngFor="let item of stateArray" value="{{item}}">{{item}}</mat-option>
        </mat-select>
      </mat-form-field>
    </div>
    <div class="col-md-3">
      <mat-form-field>
        <mat-label>City</mat-label>
        <mat-select placeholder="City" formControlName="city">
          <mat-option *ngFor="let item of citiesArray" value="{{item}}">{{item}}</mat-option>
        </mat-select>
      </mat-form-field>
    </div>
  </div>
</div>
0
0