受欢迎的博客标签

Bind RadioButton List in Angular 2

Published
Earlier I posted about how to bind Select DropDown List in Angular 2 andCascading 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 usingTypeScript 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. 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. ? 1 2 3 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. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 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,   Initialization of options array having Options class object. This array will be used to populate the radiobutton list. A property named selectedOption which is used to display the selected option on HTML. A method named getValue() called on radio button change event. It takes selected option’s id as parameter and then it assign the selected option toselectedOption 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. ? 1 2 3 4 5 6 7 8 <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 is option of options where with *ngFor it is let option of options. in is replaced with of. Even the *ngFor syntax is changed after beta 17 release. Prior to beta 17, instead of let, # 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. 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 need to import two things here, Angular’s browser bootstrap function The application root/parent component, OptionListComponent. And then call bootstrap with OptionListComponent ? 1 2 3 4 5 6 import {bootstrap} from '@angular/platform-browser-dynamic'; import { OptionListComponent } from './optionlistcomponent';   bootstrap(OptionListComponent)     .then(success => console.log(`Bootstrap success`))     .catch(error => console.log(error)); 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]. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 <!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://npmcdn.com/[email protected]/dist/zone.js"></script>     <script src="https://npmcdn.com/[email protected]/Reflect.js"></script>     <script src="https://npmcdn.com/[email protected]/dist/system.js"></script>     <script src="https://npmcdn.com/[email protected]/lib/typescript.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 postsrelated with Angular 2.  .