How To Work With Dropdown In Angular 2, 4 Using Visual Studio Code

Introduction

A few months ago, I wrote an article based on Angular 2 for beginners and today in this article, we will learn about Angular 2 with TypeScript to bind dropdown and select value from dropdown. Angular dropdown is not any big deal; it's the same as Angular 1 but here there are some differences of approach. If you are a beginner in Angular, you need to go through the article "Getting started with Angular2 using Visual Studio code"  

How to create architecture of application  -- you can go through the given link click here.
Here some prerequisites if you are going to create an Angular 2 or 4 application. To bind dropdown, we need to follow only 3-4 simple steps in Angular 2 or 4 using TypeScript.
 
Step 1

Create Angular application using TypeScript.
 
Prerequisites
Step 2

Configure as per project requirement (component, HTML page, routing, module, etc....).

Step 3

Create service to get data from API and store in an object. If you are not using service to get data, just create a simple array list to store information.

Step 4

So far, I  hope you have configured your application with all dependencies; if not, I would like to refer you to this article to create a simple architecture using system.js, config.js.
Step 5

Create a function inside your component.ts (see the code given below). Now, I am going to explain some basic points carefully.
 
Component Component is just like a TypeScript class which is using @component decorator. We can create function and logic here to create any event, variable, property.
Module  Module is just the starting point of application where we have to inject all components, services, and pipes etc.
Decorator Decorator is used to define behavior of typescript class. In Angular 2 and 4 multiple decorator are there. e.g. -
@Domponet
@Pipe
@ngModule
@ Directive and more..
each one is used in the top of the typescript class to define behavior and nature of the class. 
  1. import {  
  2.     Component,  
  3.     ViewEncapsulation  
  4. } from '@angular/core';  
  5. import {  
  6.     MyCodeService  
  7. } from '../../../../_services';  
  8. import {  
  9.     Router  
  10. } from '@angular/router';  
  11. @Component({  
  12.     selector: 'Home-component',  
  13.     templateUrl: './Home.component.html',  
  14.     encapsulation: ViewEncapsulation.None  
  15. })  
  16. export class HomeComponent {  
  17.     nameList: any;  
  18.     nameId: Number;  
  19.     constructor(private _myCodeService: MyCodeService) {  
  20.         this.getNameList();  
  21.     }  
  22.     getNameList() {  
  23.         this._myCodeService.getNameList().subscribe(data => {  
  24.             this.nameList = data;  
  25.         });  
  26.     }  
  27.     selectName() {  
  28.         alert(this.nameId);  
  29.     }  
Or if you are not using service and want to bind dummy data in dropdown (see given below code). I have created a dummy JSON which contains Name and Id of two fields, and fields are key pair value.
  1.   
  2. import { Component, ViewEncapsulation } from '@angular/core';  
  3. import { MyCodeService } from '../../../../_services';  
  4. import { Router } from '@angular/router';  
  5. @Component({  
  6. selector: 'Home-component',  
  7. templateUrl: './Home.component.html',  
  8. encapsulation: ViewEncapsulation.None  
  9. })  
  10. export class HomeComponent {  
  11. nameList: any;  
  12. data:any; 
  13. nameId:Number; 
  14. constructor( private _myCodeService : MyCodeService ) {  
  15. this.getNameList();  
  16. }  
  17. getNameList()  
  18. {   
  19. this.nameList= this.data;   
  20. }
  21. selectName()
  22. {
  23. alert(this.nameId);
  24. }  
  25. this.data=[    
  26.     {    
  27.       "Id": 3,    
  28.       "Name""Attorney Case"    
  29.     },    
  30.     {    
  31.       "Id": 1035,    
  32.       "Name""bikesh appeal"    
  33.     },    
  34.     {    
  35.       "Id": 22,    
  36.       "Name""BikeshAppeal"    
  37.     },    
  38.     {    
  39.       "Id": 20,    
  40.       "Name""Case Info"    
  41.     },    
  42.     {    
  43.       "Id": 15,    
  44.       "Name""Case Infoe"    
  45.     },    
  46.     {    
  47.       "Id": 11,    
  48.       "Name""Case Prep"    
  49.     }        
  50.   ]    
  51. }  
So in this component, I am going to bind dropdown. Once the component loads, you can replace according to your requirment. As per the above code, you need to set JSON key pair value in an array list.
 
Step 6

Create an HTML page and dropdown element to bind data (see code given below). You can see in the given code, I am using <select> element. This element is used to iterate the value and populate in options. 
  1. <div class="box-header with-border">  
  2.            <div class="form-group voffset row">  
  3.                <label for="" class="vertical-label col-sm-4 col-md-8 text-right"> Select Name</label>  
  4.                <div class="col-sm-8 col-md-4">  
  5.                    <select id="Id" #Id="ngModel" class="hideLabel form-control" [(ngModel)]="nameId" name="Id" (change)="selectName();">  
  6.                            <option selected="" value=""></option>  
  7.                         <option [ngValue]="k.Id" *ngFor="let k of nameList">  
  8.                             {{k.Name}}  
  9.                      </option>  
  10.                 </select>  
  11.                </div>  
  12.            </div>  
  13.        </div>  
Now, data is ready to populate data in dropdown. *ngFor: is used to iterate data from array.

[(ngModel)]: is use to control data and pass selected value from View to component to View and View to component (Two way binding).
 
And also, I created a function to get selected value from dropdown on change event of element. (change) is used to fire event.
So with  selectName() we are able to get selected Id from HTML element.
 
It's a very simple and fast way to bind dropdown in angular2 or 4 within 5 minutes.
 
Other References
I hope you guys learned the  approach to bind value, call function, use service and get selected value from dropdown.


Similar Articles