Angular 2 Bind DropDown List Using Web API

Introduction

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

I will be using Visual Studio as an 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 the dropdown list.

Prerequisites

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

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

CREATE TABLE [dbo].[tbl_language] (
    [languageID] INT IDENTITY(1,1) NOT NULL,
    [language] VARCHAR(200) NOT NULL,
    CONSTRAINT [PK_TBL_LANGUAGE] PRIMARY KEY CLUSTERED (
        [languageID] ASC
    ) WITH (
        PAD_INDEX = OFF,
        STATISTICS_NORECOMPUTE = OFF,
        IGNORE_DUP_KEY = OFF,
        ALLOW_ROW_LOCKS = ON,
        ALLOW_PAGE_LOCKS = ON
    ) ON [PRIMARY]
) ON [PRIMARY];

Insert some sample data into the table.

Sample data

app.component.ts

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

@Component({
    selector: 'my-app',
    templateUrl: './app/binddropdownlisteg.html'
})
export class AppComponent {
}

“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 the Web API Controller is required to get the list of the languages from the table.

Web API Controller and Method

public class languageAPIController : ApiController
{
    private db_sampleentities db = new db_sampleentities();

    // Constructor
    public languageAPIController()
    {
        // Add the following code
        // Problem will be solved
        db.Configuration.ProxyCreationEnabled = false;
    }

    // GET: api/languageAPI
    public IEnumerable<tbl_language> Gettbl_language()
    {
        return db.tbl_language.ToList();
    }
}

Here, in the code db_sampleentities given above is the datacontext class, which is used to communicate with the 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 the name languageservice.service.ts, which acts as a Service for us to call the Web API method and map the data in JSON format.

languageservice.service.ts

import { Injectable } from '@angular/core';
import { Http, Response, RequestOptions, Headers } from '@angular/http';
import { tbl_language } from '../service_models/samplemodels';
import { Observable } from 'rxjs/Rx';

@Injectable()
export class languageService {
    constructor(private http: Http) { }

    getlanguages(): Observable<tbl_language[]> {
        return this.http.get('api/languageAPI')
            .map(res => res.json())
            .catch(this.handleError);
    }

    private handleError(error: Response | any) {
        // In a real world app, we might use a remote logging infrastructure
        let errMsg: string;
        if (error instanceof Response) {
            const body = error.json() || '';
            const err = body.error || JSON.stringify(body);
            errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
        } else {
            errMsg = error.message ? error.message : error.toString();
        }
        console.error(errMsg);
        return Observable.throw(errMsg);
    }
}

The code above lets you connect to the Web API method(Getbl_language()) to extract the languages.

binddropdownlisteg.html

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

<div>
    <label>Language:</label>
    <select [formControl]="sampleform.controls['languageID']">
        <option value="0">--Select--</option>
        <option *ngFor="let lang of languages" value="{{ lang.languageID }}">
            {{ lang.language }}
        </option>
    </select>
</div>

Service Model

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

languagemodel.ts

export class tbl_language {
    languageID: number;
    language: string;
}

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 the dropdown list.

Final Code for app.component.ts file

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

// * Import the language model which contains properties for holding the data
import { tbl_language } from '../Models/languagemodel';

// * Import the name of the service we have created
import { languageService } from '../Services/languageservice.service';
import { FormBuilder, Validators, FormGroup, FormControl } from '@angular/forms';

@Component({
    selector: 'my-app',
    templateUrl: './app/binddropdownlisteg.html',
    providers: [languageService]
})
export class AppComponent {
    errorMessage: string;

    public languages: tbl_language[]; // Create a variable of type tbl_language object
    sampleform: FormGroup;

    constructor(private _languageService: languageService, fb: FormBuilder) {
        this.sampleform = fb.group({
            'languageID': [null] // Will use the property in HTML page
        });
    }

    ngOnInit() {
        // Call the method on initial load of page to bind dropdown
        this.getlanguages();
    }

    // Get the list of languages
    getlanguages() {
        this._languageService.getlanguages().subscribe(
            res => this.languages = res,
            error => this.errorMessage = <any>error
        );
    }
}

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 Angular 2, and displayed on the screen by binding the data to the dropdown list.

Web API method

Thank you for reading the article.

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


Similar Articles