Earlier I posted about how to bind Select DropDown List in Angular 2 and Cascading DropDown List using Angular 2 covering some of the newest features of Angular 2 beta 8 release. And in this post, we will find out how to bind radiobutton list in Angular 2. At the time of writing this post, Angular 2 RC4 is the newest version.
Bind RadioButton list in Angular 2
Angular 2 is awesome, clean, powerful and yet simple. The more you use it, the more you love it. For the demo, I created a sample Angular 2 application using TypeScript which binds an options list collection to radiobutton list. Below image shows, the structure of Angular 2 application.
In Angular 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 its purpose.
- options.ts: This file has a simple class called
"Options"
with 2 properties id and name. - optionlistcomponent.ts: This file contains code for defining a component and template used to render HTML. The Component adds the metadata to the class.
- optionlistcomponent.html: This file has HTML code to render the radiobutton 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
Options.ts
Nothing fancy here. Simple class with 2 properties.
export class Options { constructor(public id: number, public name: string) { } }
OptionListComponent.ts
This file has a class OptionListComponent
which creates an array of Options
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 Options
class within this file, we also import it. The @Component
annotation adds the metadata to the class.
import {Component} from '@angular/core'; import { Options } from './options'; @Component({ selector: 'my-option-list', templateUrl: 'app/optionlistcomponent.html' }) export class OptionListComponent { selectedOption:Options = new Options(2, 'T-Shirts'); options = [ new Options(1, 'Jeans' ), new Options(2, 'T-Shirts' ), new Options(3, 'Shorts' ), new Options(4, 'Shirts') new Options(5, 'Trousers') new Options(6, 'Chinos') new Options(7, 'Shoes') ]; getValue(optionid) { this.selectedOption = this.options.filter((item)=> item.id == optionid)[0]; } }
@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.
OptionListComponent (our component class) contains following,
Options
class object. This array will be used to populate the radiobutton list.selectedOption
which is used to display the selected option on HTML.getValue()
called on radio button change event. It takes selected option’s id as parameter and then it assign the selected option to selectedOption
property.OptionListComponent.html
This is the file specified in the templateURL in @Component
directive. This file contains HTML markup which you would be displayed. Since we don’t know how many options are going to be there so we can’t hardcode number of radiobutton list items. So the idea is to loop through all the options and create a radiobutton list. But how do we do that?
Well, to solve this I put a single input type radio inside an un-ordered list. And run a loop of options on it. And using css hide the bullets displayed via <li> tag. The *ngFor
structural directive is used to loop through options array. First, take a look at the code.
<ul> <li *ngFor="let option of options"> <input type="radio" name="price" (click)="getValue(option.id)" [checked]="option.id == selectedOption.id" value= {{option.id}}>{{option.name}} </li> </ul> <p>Selected Option : <strong>{{selectedOption.name}}</strong></p>
Let’s visit all new Angular 2 changes with respect to above code.
- camelCase syntax is used.
- Asterisk(*) sign is used as prefix for structural directives.
ng-repeat
used in Angular 1.x for looping is replaced with*ngFor
.- With
ng-repeat
the syntax isoption of options
where with*ngFor
it islet option of options
.in
is replaced withof
. Even the *ngFor syntax is changed after beta 17 release. Prior to beta 17, instead oflet
,#
was used. Like#option in options
. - One way data binding is achieved via putting attribute in square bracket[]. For example,
[checked]
ng-click
is no longer valid in Angular 2. It is now(click)
.
Please read my post to know about Difference between Angular 1.x and Angular 2.
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 likeNgIf
andNgFor
which become immediately visible and usable in any of this modules component templates. - 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 thedeclarations
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 '@angular/core' import {BrowserModule} from '@angular/platform-browser' import { OptionListComponent } from './optionlistcomponent'; @NgModule({ imports: [ BrowserModule ], declarations: [ OptionListComponent ], bootstrap: [ OptionListComponent ] }) 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
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import {AppModule} from './app'; platformBrowserDynamic().bootstrapModule(AppModule)
This code can also be moved to OptionListComponent.ts
but putting it in a separate file is a 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. Now for showing the radiobutton list, we need to add the selector my-option-list
defined in the component class in our HTML page. [line number: 22].
<!DOCTYPE html> <html> <head> <title>Angular 2 Bind radio button list demo</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <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://unpkg.com/reflect-metadata@0.1.3/Reflect.js"></script> <script src="https://unpkg.com/systemjs@0.19.31/dist/system.js"></script> <script src="config.js"></script> <script> System.import('app').catch(function(err){ console.error(err); }); </script> </head> <!-- 3. Display the application --> <body> <h2>Angular 2 Bind radio button list demo</h2> <my-option-list>Loading...</my-option-list> </body> </html>
You can also check all the code and demo at Plunker. Also read my other posts related with Angular 2.
Thank you for reading. Keep visiting this blog and share this in your network. Please put your thoughts and feedback in the comments section.
Hello, great tutorial but I have one question :). Why do you pass id to onClick function and then search for first element of array? Wouldn’t it be easier to just pass option that you already have in ngFor loop?
Thanks 🙂