How To Bind DropDownList From API With Validation In Angular

In this blog, we will learn about how to bind the Drop-Down List from API in Angular and how to apply the required validation on it.

A Drop-Down List is used for selecting value out of many values or list of value, let’s say categories of food like Starter, Main Course.out of them the user may select one at a time.

Prerequisites:

  • Basic knowledge of Angular
  • Code editor like Visual Studio Code

Create a new Angular project by typing the following command in the VSCode terminal.

ng new bind-dropdownlist

as we are applying validation and for better and responsive design, we need to add Bootstrap 4 to our Angular app.please click the link given below and follow the steps to add Bootstrap 4.

Add Bootstrap 4, jQuery and Font Awesome To Angular

Note: You must have to add jQuery because Bootstrap uses jQuery for JavaScript plugins.

Open the app.module.ts file and import HttpClientModule and FormsModule in it. as we are going to call API or making HTTP call for getting data from API and adding the required field validation on the drop-down list. Please refer following code.

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';

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

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

Open the app.component.ts file and add the following code in it.

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

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

  Categories: {};

  constructor(private http:HttpClient) {
    this.GetCategoryList();
  }

  title = 'bind-dropdownlist';
  ddlCategory = "";

  onSubmit() {
    alert('Category ID: ' + this.ddlCategory);
  } 

  GetCategoryList(){
    this.http.get(`http://localhost:61651/api/Category`).subscribe(
      data => this.Categories = data
    );
  }
  
}

in the above code, we need to import HttpClient for making an API call and define private http:HttpClient as a parameter in the constructor. define the “Categories” variable in which we store a list of categories that we will get from API response.

made one function GetCategoryList() which will call API for getting data and store it in the Categories variable. we will use this variable for the binding list into a dropdown. call GetCategoryList() from constructor so it will call API and get data every time the page is loaded. define the ddlCategory variable in that we will store selected category value from the dropdown.

The response format of API which we got from GetCategoryList() is as follows.

[{CategoryId: 1, CategoryName: "Starter"}
{CategoryId: 2, CategoryName: "Soups"}
{CategoryId: 3, CategoryName: "salads"}
{CategoryId: 4, CategoryName: "Main Course"}]

Now, open the app.component.html and add the following code in it.

<div class="card-container">
  
    <form name="form" (ngSubmit)="form.valid && onSubmit()" #form="ngForm">
      <div class="form-group">
        <label for="DDCategory">Category Dropdown</label>
        <!-- DropDownList -->
        <select class="custom-select" name="DDCategory" [(ngModel)]="ddlCategory" #DDCategory="ngModel" 
        [ngClass]="{ 'is-invalid': form.submitted && DDCategory.invalid }" required>
          <option value="" class="text-primary font-weight-bolder">
            --- Select Category ---
          </option>
          <option *ngFor="let Category of Categories" [value]="Category.CategoryId">
            {{Category.CategoryName}}
          </option>
        </select>
        
        <!-- Required Validation Message -->
        <div *ngIf="form.submitted && DDCategory.invalid" class="text-danger">
          <h6 *ngIf="DDCategory.errors.required">Category is Required</h6>
        </div>
      </div>

      <button class="btn btn-primary">Submit</button>
    </form>

  </div>

Your dropdown list is ready for use. just follow the above step properly and you will get the result.

Output:

 

 

 

2 Comments

  1. ekrem Hacıbektasoglu

    nice arcticle

    but I dont understand this dropdown binding from json file or mongoose db

    thank you

    0
    0
    Reply
  2. kumar

    Hi,

    Can you share the Full source code with github link?

    0
    0
    Reply

Submit a Comment

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

Subscribe

Select Categories