Step by step guide line to create cascading drop-down list using the Angular 15 and WEB API Core 6.

Step by step guide line to create cascading drop-down list using the Angular 15 and WEB API Core 6.

Step by step guide line to create cascading drop-down list using the Angular 15 and WEB API Core 6.

 

Introduction:

The cascading DropDownList is a series of DropDownList, where the value of one DropDownList depends upon another’s selected value. This can be configured by using the change event of the parent DropDownList.


Within that change event handler, data has to be loaded to the child DropDownList based on the selected value of the parent DropDownList.

 

To get started We create a WebAPI project using MVC Core 6.

For this purpose, we create two models like below:

 

public class InstituteType

    {

        public int Id { get; set; }

        [Required]

        [StringLength(40)]

        public string TypeName { get; set; }

        public string TypeDescription { get; set; }

        [ValidateNever]

        public ICollection<Institute> Institutes { get; set; }

    }

public class Institute

    {

        [Key]

        public int Id { get; set; }

        [Required]

        [StringLength(120)]

        public string InstituteName { get; set; }

        [Required]

        [StringLength(8)]

        public string ShortName { get; set; }

        [Required]

        [StringLength(120)]

        public string ContactNumber { get; set; }

        public string AdminEmail { get; set; }

        public string AdminEmailPassword { get; set; }

        public string Address { get; set; }

        public string LogoPath { get; set; }

        [NotMapped]

        public IFormFile LogoImage { get; set; }

        public string BannerPath { get; set; }

        [NotMapped]

        public IFormFile BannerImage { get; set; }

        [ForeignKey("InstituteType")]

        public int InstituteTypeId { get; set; }

        public Ownership Ownership { get; set; }   

        [ValidateNever]

        public InstituteType InstituteType { get; set; }

        public ICollection<TopMenu> TopMenus { get; set; }

    }

 

 

 Write Action method in API controller class to retrieve records from InstituteType & Institute table.

[HttpGet]

        public IEnumerable<InstituteType> GetAll()

        {

            return this.unitofWork.InstituteTypeRepository.GetAll(null,includeProperties: "Institutes");

        }

 

  [HttpGet]

        [Route("GetByType")]

        public IEnumerable<Institute> GetByType(int typeId)

        {

            List<Institute> all = new List<Institute>();

            try

            {

                if (typeId>0)

                {

                    all = this.unitofWork.InstituteRepository.GetAll(t=>t.InstituteTypeId==typeId, null).ToList();

                }

                

            }

            catch (Exception ex)

            {

                all = new List<Institute>();

            }

            return all;

        }

        Create angular Project and open in Visual Studio Code.

 

 

           

          Create component <CascadingDropdownEx>, open component and write following code in .ts file

 

CascadingDropdownEx.ts

import { HttpClient } from '@angular/common/http';

import { Component,OnInit } from '@angular/core';

 

@Component({

  selector: 'app-cascading-dropdown-ex',

  templateUrl: './cascading-dropdown-ex.component.html',

  styleUrls: ['./cascading-dropdown-ex.component.css']

})

export class CascadingDropdownExComponent implements OnInit{

alltypes:any=[]

allins:any=[]

isData:boolean=false;

constructor(private http:HttpClient){}

ngOnInit(): void {

  this.http.get("https://localhost:7039/api/InstituteTypes").subscribe((res)=>{

  this.alltypes=res

  console.log(res)

  },(er)=>{console.log(er)})

}

getCascadeDropdown(v:any){

console.log(v)

  console.log(v.target.value)

  this.http.get("https://localhost:7039/api/Institutes/GetByType?typeId="+v.target.value).subscribe((res)=>{

    this.allins=res

    console.log(res)

   

   if (! this.allins || this.allins == 0 ) {

    this.isData=false;

    // do something

}

else

{

  this.isData=true;

}

    console.log(this.isData)

    },(er)=>{console.log(er)})

}

}

 

 

Note:  to use HttpClient we have to add HttpClientModule in imports section of app.module.ts and import like below:

App.module.ts

import{HttpClientModule} from '@angular/common/http';

 

 imports: [

    BrowserModule,

    AppRoutingModule,

    HttpClientModule

  ]

 

 

           

          Write following code in HTML of respected component

 

 

cascading-dropdown-ex.component.html

<div id="main">

    <p>cascading-dropdown-ex works!</p>

    <select (change)="getCascadeDropdown($event)" >

        <option>Select Type </option>

        <option value="{{item.Id}}" *ngFor="let item of alltypes">{{item.TypeName}}</option>

    </select>

<br/>

    <select *ngIf="isData " >

        <option>Select Institute </option>

        <option value="{{item.Id}}" *ngFor="let item of allins">{{item.InstituteName}}</option>

    </select>

</div>

 

In the above file I have done binding by allins. Which contains all types. Depending on selected types next dropdown will be loaded. Which contain all institute name of selected types. Here I also take a Boolean type variable isData.  isData will true if there any institute of selected type. If no institute then it will false and second dropdownlist will be hide. That mean if isData  true Second dropwonlist will be visible with records otherwise second dropdownlist will be invisible.

Back to Blogs