Skip to main content
Bind Select DropDown List in Angular JS 2

Bind Select DropDown List in AngularJS 2

Earlier I posted about difference between AngularJS 1.x and AngularJS 2 in which I tried to explain how things changed with respect to AngularJS 2.And in this post, we shall find out how to bind select dropdown list in AngularJS 2.

UPDATE(6-Dec-2016): Updated to Angular 2 RTM release.

Also read,

Bind select dropdown list in AngularJS 2

For demo, I created a sample AngularJS 2 application using TypeScript which binds the country list collection to select dropdown list. Below image shows, the structure of AngularJS 2 application. Read TypeScript Interview Questions to get started with TypeScript.

Bind Select DropDown List in AngularJS 2
In AngularJS 2, controllers and $scope are replaced with “Components” and you think everything in terms of classes. Now, let’s see each file’s code and it’s purpose.

  • country.ts: This file has a simple class called “Country” with 2 properties id and name.
  • countrylistcomponent.ts: This file contains code for defining a component and template used to render HTML. The Component adds the metadata to the class.
  • countrylistcomponent.html: This file has HTML code to render select dropdown list.
  • app.ts: This file contains code to of Angular 2 root module. Every angular 2 application is having a root module. This was introduced in RC 5 release.
  • main.ts: This file contains code to bootstrap angular 2 in our application.
  • config.js: This file contains code to load angular 2 and all its required packages.

Code Walk-through

Country.ts

Nothing fancy here. Simple class with 2 properties.

export class Country {
  constructor(public id: number, public name: string) { }
}

CountryListComponent.ts

This file has class CountryListComponent which creates an array of Country class and populate the data. Angular apps are modular and Angular itself is modular. So to use @Component directive, we first need to import the library. The very first statement imports it and similarly to use Country class within this file, we also import it. The @Component annotation adds the metadata to the class.

import {Component, NgModule} from [email protected]/core'
import {BrowserModule} from [email protected]/platform-browser'
import { Country } from './country';

@Component({
  selector: 'my-country-list',
  templateUrl: 'app/countrylistcomponent.html'
})
export class CountryListComponent {
  selectedCountry:Country = new Country(2, 'India');
  countries = [
     new Country(1, 'USA' ),
     new Country(2, 'India' ),
     new Country(3, 'Australia' ),
     new Country(4, 'Brazil')
  ];
}

@Component metadata object has two fields, a selector and a template.

  • The selector specifies a selector for an HTML element that represents the component.
  • The template tells Angular how to render this component’s view. There can be a URL of HTML file or you can also put HTML here. For this demo, I put URL to HTML file.

There is also a class named CountryListComponent, which is your component class. And within this class, initialization of countries array is done. And here Country class is also used for populating country.

CountryListComponent.html

This is file which specified in the templateURL for @Component directive. In this file, there is a select HTML element and within the option, *ngFor structural directive is used. With Angular 1.x, ng-repeat was used for looping purpose but things changed in Angular 2. Let’s visit all new changes with respect to below code.

  • ng-repeat is replaced with *ngFor
  • Asterisk(*) sign is used as prefix for structural directives
  • With ng-repeat the syntax is country in countries where with *ngFor it is let country of countries.. in is replaced with of.
  • camelCase syntax is used.
  • In Angular 2, local variables are defined using hash(#) prefix.
<select>
  <option *ngFor="let country of countries" value= {{country.id}}>
    {{country.name}}
  </option>
</select>

app.ts

Every Angular app has a root module class. By convention it’s a class called AppModule.

  • First, import all the required things.
  • The @NgModule decorator defines the metadata for the module. BrowserModule registers critical application service providers. It also includes common directives like NgIf and NgFor which become immediately visible and usable in any of this modules component templates.FormsModule is required for ngModel directive.
  • The declarations list identifies the application’s only component, the root component, the top of this app’s rather bare component tree. we can list the components, directives and pipes that are part of the module in the declarations array.
  • Import other modules by listing them in the imports array.
  • The bootstrap property should have the name of root component that should be used as bootstrap entry points for the application.
//our root app component
import {Component, NgModule} from [email protected]/core'
import {BrowserModule} from [email protected]/platform-browser'
import { FormsModule } from [email protected]/forms';
import { CountryListComponent } from './countrylistcomponent';

@NgModule({
  imports: [ BrowserModule, FormsModule ],
  declarations: [ CountryListComponent ],
  bootstrap: [ CountryListComponent ]
})
export class AppModule {}

Please read following post to understand more about NgModule.

Main.ts

This file has code to bootstrap Angular 2 in our application. Remember ng-app is no longer available. The only way to bootstrap Angular 2 is via code. We launch the application by bootstrapping the AppModule in the main.ts file. We need to import two things here,

  • Angular’s browser bootstrap function
  • The application root/parent module, which is Appmodule. This is new in Angular 2. Every Angular 2 application is now having a root module.

And then call bootstrap with AppModule

//main entry point
import {platformBrowserDynamic} from [email protected]/platform-browser-dynamic';
import {AppModule} from './app';

platformBrowserDynamic().bootstrapModule(AppModule)

This code can also be moved to CountryListComponent.ts but putting it in separate file is proper way to structure any Angular application. As App bootstrapping is a separate concern, and we should not mix it with other code.

Index.html

And finally index.html where actual magic happens. All the required dependencies are refereed. And I am using SystemJs to load the application and modules. You can read about how to configure it here. config.js file contains all the code to load angular 2 and its packages. And also the selector defined in component is placed in this file [line number: 19].

<!DOCTYPE html>
<html>
  <head>
    <base href="." />
    <title>Angular 2 Bind select list demo</title>
    <link rel="stylesheet" href="style.css" />
    <script src="https://unpkg.com/zone.js/dist/zone.js"></script>
    <script src="https://unpkg.com/zone.js/dist/long-stack-trace-zone.js"></script>
    <script src="https:[email protected]/Reflect.js"></script>
    <script src="https:[email protected]/dist/system.js"></script>
    <script src="config.js"></script>
    <script>
    System.import('app')
      .catch(console.error.bind(console));
  </script>
  </head>
  <body>
   <h2>Angular 2 Bind select list demo</h2>
     <my-country-list>Loading....</my-country-list>
  </body>
</html>

In the CountryListComponent class, there is a property defined named selectedCountry and it is set to a new Country Class object. So now, you can use this property to show selected country on load. All you need to use is [(ngModel)] directive. Notice, the syntax is also changed for two-way binding in AngularJS 2.

<select [(ngModel)]="selectedCountry.id">
  <option *ngFor="let country of countries" value= {{country.id}}>
     {{country.name}}
  </option>
</select>

You can also check all the code and demo at plunkr.

I also enhanced this AngularJS 2 application and shown how to implement Cascading DropDown List using AngularJS 2 . Also read Bind RadioButton List in Angular 2.

Thank you for reading. Keep visiting this blog and share this in your network. Please put your thoughts and feedback in comments section.

7 thoughts on “Bind Select DropDown List in AngularJS 2

  1. In the Plunker you link to I added a label to mirror the selection but it doesn’t work if I try to mirror the country name. It only works with the country id. Why is that?

Leave a Reply to shiz Cancel reply

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

8 + 2 =