Angular 2 Bind DropDown List Using Web API

Introduction

This article explains how to bind dropdown list by getting data from database using Web API.

I will be using Visual Studio as IDE to start with the project. If you are not sure about how to start with an Angular 2 project, using Visual Studio, have a look at the article given below.

After creating the project in Visual Studio, you will find an app.component.ts file, where we will be calling the external HTML file, which has a code to bind dropdown list.

Prerequisites

I am assuming that you know how to use an Entity Framework to fetch/ save the data and I have used Database First approach to create models in this Application.

Create a table in SQL Server database, which is used to hold the data for our languages. Find the script given below for the table. 

  1. CREATE TABLE [dbo].[tbl_language](  
  2.     [languageID] [int] IDENTITY(1,1) NOT NULL,  
  3.     [language] [varchar](200) NOT NULL,  
  4.  CONSTRAINT [PK_TBL_LANGUAGE] PRIMARY KEY CLUSTERED   
  5. (  
  6.     [languageID] ASC  
  7. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  8. ON [PRIMARY]   

Insert some sample data into the table.

Angular2

app.component.ts 

  1. import { Component } from '@angular/core';  
  2.   
  3.   
  4. @Component({  
  5.     selector: my-app',  
  6.     templateUrl: './app/binddropdownlisteg.html'  
  7.       
  8. })  
  9. export class AppComponent {  
  10. }   

“app.Component.ts” is the file, which is available for you when you have created your Angular 2 app in an app/app.component.ts file.

Now, create an empty Web API Controller in your Visual Studio by right clicking on the project - > Add new item - > select Empty Web API Controller from Visual Studio .

Add the code given below, where Web API Controller is required to get the list of the languages from the table.

Web API Controller and Method 

  1. public class languageAPIController : ApiController  
  2. {  
  3.     private db_sampleentities db = new db_sampleentities ();  
  4.   
  5.     // constructor  
  6.     public languageAPIController ()  
  7.     {  
  8.         // Add the following code  
  9.         // problem will be solved  
  10.         db.Configuration.ProxyCreationEnabled = false;  
  11.     }  
  12.   
  13.     // GET: api/languageAPI  
  14.       
  15.  public IEnumerable<tbl_language> Gettbl_language()  
  16.     {  
  17.         return db.tbl_language.ToList();  
  18.     }   

Here, in the code db_sampleentities given above is the datacontext class, which is used to communicate with SQL Server database to fetch the records from the database.

“tbl_language“ is the model, which will hold properties “languageID” and “language” to map with the table tbl_language columns, which we have created in the database.

Service

Create a new TypeScript file in Visual Studio with name languageservice.service.ts, which acts as a Service for us to call Web API method and map the data in JSON format.

languageservice.service.ts 

  1. import { Injectable } from '@angular/core';  
  2. import { Http, Response, RequestOptions, Headers } from '@angular/http';  
  3. import { tbl_language } from '../service_models/samplemodels';  
  4. import { Observable } from 'rxjs/Rx';  
  5.   
  6. @Injectable()  
  7. export class languageService  
  8. {  
  9.   
  10.     constructor(private http: Http) { }  
  11.       
  12.     getlanguages(): Observable<tbl_language[]> {  
  13.         return this.http.get('api/languageAPI)  
  14.             .map(res => res.json())  
  15.             .catch(this.handleError);  
  16.     }    
  17.      
  18.   
  19.     private handleError(error: Response | any) {  
  20.         // In a real world app, we might use a remote logging infrastructure  
  21.         let errMsg: string;  
  22.         if (error instanceof Response) {  
  23.             const body = error.json() || '';  
  24.             const err = body.error || JSON.stringify(body);  
  25.             errMsg = `${error.status} - ${error.statusText || ''} ${err}`;  
  26.         } else {  
  27.             errMsg = error.message ? error.message : error.toString();  
  28.         }  
  29.         console.error(errMsg);  
  30.         return Observable.throw(errMsg);  
  31.     }  
  32. }   

The code iven above lets you connect to get an operation in Web API to extract the languages.

binddropdownlisteg.html

Create an HTML file in the Application to display the dropdown, add the code given below, which will fetch the data by looping through the languages data. 

  1. <div>  
  2.    <label>Language:</label>  
  3.        <select  [formControl]="sampleform.controls['languageID']">  
  4.                                 <option value="0">--Select--</option>  
  5.                                 <option *ngFor="let lang of languages"  
  6.                                         value={{lang.languageID}}>  
  7.                                     {{lang.language}}  
  8.                                 </option>  
  9.          </select>  
  10.    </div>    

Service Model

Create a TypeScript file and name it languagemodel.ts, which has properties to hold the data from Web API.

languagemodel.ts

  1. export class tbl_language {  
  2.     languageID: number;  
  3.     language: string;  
  4.   
  5. }  

Now, open an app.component.ts file and change the code to include the Service and Model, which we have created in an AppComponent class to bind dropdown list.

Final Code for app.component.ts file

  1. import { Component } from '@angular/core';  
  2.   
  3. // *import the language model which contains properties for holding the data  
  4. import { tbl_language } from '../Models/languagemodel;  
  5.   
  6. // * import the name of service we have created  
  7. import { languageService } from '../Services/languageservice.service';   
  8. import { FormBuilder, Validators, FormGroup, FormControl } from '@angular/forms';  
  9.   
  10. @Component({  
  11.     selector: my-app',  
  12.     templateUrl: './app/binddropdownlisteg.html'  
  13.     providers: [languageService]  
  14. })  
  15. export class AppComponent {  
  16.   
  17. errorMessage: string;  
  18.      
  19.     public languages: tbl_language[]; // create a variable of type tbl_language object  
  20.     sampleform: FormGroup;  
  21.   
  22.     constructor(private _ languageService: languageService,fb: FormBuilder) {  
  23.         this. sampleform = fb.group({  
  24.         'languageID': [null]   // will use the property in html page  
  25.         })  
  26.   
  27.     }  
  28.   
  29.     ngOnInit()  
  30.     {  
  31.   
  32.       // call the method on initial load of page to bind dropdown   
  33.     
  34.         this.getlanguages();  
  35.      
  36.   
  37.     }  
  38.   
  39.   
  40.     //Get the list of languages  
  41.   
  42.     getlanguages() {  
  43.         this._ShortuesService.getlanguages().subscribe(res => this.languages = res, error => this.errorMessage = <any>error);  
  44.     }  
  45.    
  46.   
  47.       
  48. }  

Summary

Run the Application by pressing F5 and you can see the output with the the values drowndown list.

In this tutorial, we created a table with the languages, a Web API method to fetch the languages, subscribed to the data in an Angular 2 and displayed on the screen by binding the data to dropdown list.


Thank you for reading the article.

In case of any feedback or an issue, please comment below.