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.
- 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.
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 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 ();
-
-
- public languageAPIController ()
- {
-
-
- db.Configuration.ProxyCreationEnabled = false;
- }
-
-
-
- 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 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
- 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) {
-
- 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 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.
- <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 dropdown list.
Final Code for app.component.ts file
- import { Component } from '@angular/core';
-
-
- import { tbl_language } from '../Models/languagemodel;
-
-
- 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[];
- sampleform: FormGroup;
-
- constructor(private _ languageService: languageService,fb: FormBuilder) {
- this. sampleform = fb.group({
- 'languageID': [null]
- })
-
- }
-
- ngOnInit()
- {
-
-
-
- this.getlanguages();
-
-
- }
-
-
-
-
- getlanguages() {
- this._ShortuesService.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 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.