In this tutorial, I am gonna discuss that how we can create cascade dropdowns using arrays in angular.
Step1: First I will create a model.ts file to declare and define the model for program
export class Department { id: number; name: string; } export class employee { eid: number; empname: string; did : number; }
In this model, I have created two model classes, first Department class is dedicated for department dropdown and second one employee class for second drop-down control. This task will be done just like primary and foreign key relationships in which id is working as a primary key and did is working as foreign key.
Note: Never forget to pass the reference of FormsModule into app.module.ts otherwise ngModel data binding will not work.
Step 2. Pass reference of the model into a component class where we want to implement cascade dropdowns.
import { Component, OnInit } from '@angular/core'; // Reference of model classes import { Department , employee} from './model'; @Component({ selector: 'app-dropdownex', template: ` <div class="form-group"> <label for="department">Department</label> <select id="department" (change) = "changedata($event)" [(ngModel)]="department" class="form-control"> <option *ngFor="let dept of departments" [value]="dept.id"> {{dept.name}} </option> </select><br/> <label for="emp">Employees</label> <select id="emp" class="form-control"> <option *ngFor="let empobj of finaldata"> {{empobj.empname}} </option> </select> </div> `, styles: [] }) export class DropdownexComponent implements OnInit { // Initilize Department Class departments: Department[] = [ { id: 1, name: 'Help Desk' }, { id: 2, name: 'HR' }, { id: 3, name: 'IT' }, { id: 4, name: 'Payroll' } ]; // Initilize employee class emps: employee[] = [ { eid: 1, empname: 'Help Desk' , did : 1 }, { eid: 2, empname: 'Help Desk1' , did : 2 }, { eid: 3, empname: 'Help Desk2' , did : 2 }, { eid: 4, empname: 'Help Desk3' , did : 3 }, { eid: 5, empname: 'Help Desk4' , did : 4 } ]; // create an array to stored filtered data which will be added into second dropdown public finaldata : any[] = []; constructor() { } // Following event will be called when user select item in first dropwdown. changedata($event) { // To remove previous selected items from second dropdown this.finaldata.splice(0); // Filter items and pass into finaldata this.finaldata = this.emps.filter(x=>x.did == $event.target.value); } ngOnInit() { } }
Output: