In Focus

AngularJS 2.0 From Beginning - Input Data Binding - Day Four

In this article, we will discuss about the input data binding process in AngularJS 2.0.

I am here to continue the discussion around AngularJS 2.0. Today, we will discuss input data binding in AngularJS 2. Also, in case you did not have a look at the previous articles of this series, go through the links, mentioned below.

In my previous article, I already discussed about the different processes of data binding techniques in Angular 2.0. Now, in this article, I will discuss about the process through which we can pass information or values within a component. Since in Angular 2.0, components are the core objects of the Angular framework, it is very common concern for all of us that how we can pass the data into the component in order for us to dynamically manipulate or configure the component. In the world of web development, static components will not fulfill all our requirement. So for that reason, we need to develop dynamic component or non-static component which can take data from its parent component.

Component Hierarchy

Angular 2.0 is actually made of a nested or hierarchical component structure – that means Angular 2.0 basically begins with a root component which contains all the child components of the application. Components act as self-contained because normally, we want to encapsulate our component variables and functions; and we never want that the other code to arbitrary reaches our code or value to check the changes, done in the component. Also, as a developer, I always want that our component should not hamper any other component objects used in other areas or along with my components. At the same time, component may need to share data. In Angular 2.0, a component can receive any type of data from its parent component as a receiving component.

In the above structure, each cycle structure represents a component and technically, this presentation is called as graph – a data structure, consisting of nodes and its connecting edges. The line structure represents the data flow from one component and as we can see, the data flow is in one direction i.e. from top to downwards (means from parent component to child components). This kind of structure always has some important advantages :- i.e. it is very much predictable and also it is simple to traverse and it is very easy to understand what has happened when a change is made in the parent component. In Angular point of view, when data changes in the parent node, it is very easy to find what changes are occurred in the child component.

For implementing this concept, Angular 2.0 introduces a property of @component decorator, to pass the data from parent component to child components. In Angular 2, we also can specify the data type of input data so that parent component can always pass the proper data to the child component. For defining input property of a component, we need to remember the following points. 

  1. The input property is passed to the @component decorator to pass the data.
  2. The component displays the input property in the view, but when we want to access the input property within the constructor of the constructor, then we found that it is not defined yet. This is because input properties are not available until the view has rendered which happened after the constructor function execution. Basically the values of input properties can be found either within ngOnInit() or ngAfterViewInit().

To declare input property, we need to first import the input command from Angular core module and then, use @Input decorator for declaring that property. @Input decorator takes a string type argument for specify the custom property name to provide custom component attribute name.

For demonstrating this input, we basically create an email register component as a child component and then place that component within a parent component page to pass input values. For this, create the below mentioned files.

Step 1

Create a TypeScript file named app.component.emailbox.ts and write down the below code. 
  1. import { Component, Input } from '@angular/core';  
  2.   
  3. @Component({  
  4.     selector: 'email-box',  
  5.     template:'<input placeholder="{{email}}"/><button class="btn-clear">Register</button>'  
  6. })  
  7.   
  8. export class EmailBoxComponent {  
  9.   
  10.     @Input('place-holder')  
  11.     email: string = "Type your email..";  

Step 2

Now, create another TypeScript file called app.component.parent.ts and write down the below code.
  1. import { Component, OnInit } from '@angular/core';  
  2.   
  3. @Component({  
  4.     moduleId: module.id,  
  5.     selector: 'my-app',  
  6.     templateUrl: 'app.component.parent.html',  
  7. })  
  8.   
  9. export class ParentComponent implements OnInit {  
  10.     constructor() { }  
  11.   
  12.     ngOnInit() { }  

Step 3

Now, create an HTML file named app.component.parent.html and write down the below code.
  1. <div>  
  2.     <h1 class="badge">For subscription, register you email address :</h1>  
  3.     <br />  
  4.     <br />  
  5.     <email-box></email-box><br />  
  6.     <email-box [place-holder]="'Put your email'"></email-box><br />  
  7.     <email-box place-holder="Put your office email"></email-box><br />  
  8. </div> 
Here, place-holder basically is the input property which takes the place holder value of the text box. 

Step 4

Now, create another TypeScript file named app.module.ts and write down the below code.
  1. import { NgModule } from '@angular/core';  
  2. import { FormsModule } from '@angular/forms';  
  3. import { BrowserModule } from '@angular/platform-browser';  
  4.   
  5. import { ParentComponent } from './src/app.component.parent';  
  6. import { EmailBoxComponent } from './src/app.component.emailbox';  
  7.   
  8. @NgModule({  
  9.     imports: [BrowserModule, FormsModule],  
  10.     declarations: [ParentComponent, EmailBoxComponent],  
  11.     bootstrap: [ParentComponent]  
  12. })  
  13. export class AppModule { } 
Step 5

Now, create another TypeScript file named main.ts and write down the below code.
  1. import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';  
  2.   
  3. import { AppModule } from './app.module';  
  4.   
  5. const platform = platformBrowserDynamic();  
  6. platform.bootstrapModule(AppModule); 
Step 6

Now, create another HTML file named index.html and write down the below code.
  1. <!DOCTYPE html>
  2. <html>  
  3.   <head>  
  4.     <title>Angular2</title>  
  5.     <meta charset="UTF-8">  
  6.     <meta name="viewport" content="width=device-width, initial-scale=1">  
  7.     <link rel="stylesheet" href="../styles.css">  
  8.   
  9.     <!-- Polyfill(s) for older browsers -->  
  10.     <script src="../node_modules/core-js/client/shim.min.js"></script>  
  11.     <script src="../node_modules/zone.js/dist/zone.js"></script>  
  12.     <script src="../node_modules/reflect-metadata/Reflect.js"></script>  
  13.     <script src="../node_modules/systemjs/dist/system.src.js"></script>  
  14.   
  15.     <script src="../systemjs.config.js"></script>  
  16.     <script>  
  17.       System.import('app').catch(function(err){ console.error(err); });  
  18.     </script>  
  19.   </head>  
  20.   
  21.   <body>  
  22.     <my-app>Loading...</my-app>  
  23.   </body>  
  24. </html> 
Now, run the index.html file in the browser and see the out put.
 
Here, 

Now, we want to simply update the email register component with event handling. For this, do the following.

Step 1

First, add another TypeScript file named app.component.emailboxevent.ts and write down the below code.
  1. import { Component, Input } from '@angular/core';  
  2.   
  3. @Component({  
  4.     selector: 'email-box-event',  
  5.     template: '<input placeholder="{{email}}" #emailbox/><button class="red" (click)="register(emailbox)">Register</button>',  
  6.     styles: [".red {color:red;}"]  
  7. })  
  8.   
  9. export class EmailBoxEventComponent {  
  10.     @Input('place-holder')  
  11.     email: string = "Type your email..";  
  12.   
  13.     register(txtEmail) {  
  14.         console.log('Email Address resgister properly...');  
  15.         if (txtEmail.value == '') {  
  16.             alert('Put your email address first..');  
  17.             return;  
  18.         }  
  19.         else {  
  20.             alert('Your email address is :' + txtEmail.value);  
  21.             txtEmail.value = '';  
  22.         }  
  23.     }  

Step 2

Now, add another TypeScript file for another type of email register component with the name app.component.emailregister.ts and add the below code.
  1. import { Component, Input } from '@angular/core';  
  2.   
  3. @Component({  
  4.     moduleId : module.id,  
  5.     selector: 'email-register',  
  6.     templateUrl: './app.component.emailregister.html',  
  7.     styleUrls: ['../style/style.css']  
  8. })  
  9.   
  10. export class EmailRegisterComponent {  
  11.     @Input('caption1') caption1: string = '';  
  12.     @Input() caption2: string = '';  
  13.   
  14.     name: string = '';  
  15.     email: string = '';  
  16.   
  17.     register() : void {  
  18.         if (this.name != '' && this.email != '') {  
  19.             alert(this.name + ' Your email address ' + this.email + ' has been register.');  
  20.             this.clear();  
  21.         }  
  22.         else {  
  23.             alert('Fill all the fields')  
  24.         }  
  25.     }  
  26.   
  27.     clear(): void {  
  28.         this.name = '';  
  29.         this.email = '';  
  30.     }  

Step 3

Now, add an HTML file named app.component.emailregister.html and add the below code.
  1. <div style="width:40%;">  
  2.     <fieldset>  
  3.         <h2>Email Registeration</h2>  
  4.         <table style="width:100%">  
  5.             <tr>  
  6.                 <td><span>{{caption1}}</span></td>  
  7.                 <td><input type="text" [(ngModel)]="name" /></td>  
  8.             </tr>  
  9.             <tr>  
  10.                 <td><span>{{caption2}}</span></td>  
  11.                 <td><input type="text" [(ngModel)]="email" /></td>  
  12.             </tr>  
  13.             <tr>  
  14.                 <td><input type="button" value="Register" class="blue" (click)="register()"/></td>  
  15.                 <td><input type="button" value="Cancel" class="red" (click)="clear()" /></td>  
  16.             </tr>  
  17.         </table>  
  18.     </fieldset>  
  19. </div> 
Step 4

Change the code of app.component.parent.html file as below.
  1. <div>  
  2.     <h1 class="badge">For subscription, register you email address :</h1>  
  3.     <br />  
  4.     <br />  
  5.     <email-box></email-box><br />  
  6.     <email-box [place-holder]="'Put your email'"></email-box><br />  
  7.     <email-box place-holder="Put your office email"></email-box><br />  
  8. </div>  
  9.   
  10. <div>  
  11.     <br />  
  12.     <h2>Email Register control with Events</h2>  
  13.     <email-box-event [place-holder]="'Put your email'"></email-box-event><br />  
  14.     <hr />  
  15.     <br />  
  16.     <email-register [caption1]="'Your Name'" caption2="Email Id"></email-register>  
  17. </div> 
Step 5

Change the code of app.module.ts file as below.
  1. import { NgModule } from '@angular/core';  
  2. import { FormsModule } from '@angular/forms';  
  3. import { BrowserModule } from '@angular/platform-browser';  
  4.   
  5. import { ParentComponent } from './src/app.component.parent';  
  6. import { EmailBoxComponent } from './src/app.component.emailbox';  
  7. import { EmailBoxEventComponent } from './src/app.component.emailboxevent';  
  8. import {  EmailRegisterComponent } from './src/app.component.emailregister';  
  9.   
  10. @NgModule({  
  11.     imports: [BrowserModule, FormsModule],  
  12.     declarations: [ParentComponent, EmailBoxComponent, EmailBoxEventComponent, EmailRegisterComponent],  
  13.     bootstrap: [ParentComponent]  
  14. })  
  15. export class AppModule { } 
Now, write down the below code and the output as below.