AngularJS 2.0 From The Beginning - Output Property Binding - Day Five

I am here to continue the discussion around AngularJS 2.0. Today, we will discuss the output property 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 including input property binding mechanism in case of components within Angular 2.0. Now in this article, I will discuss about the process through which we can return the data to the parent component from the child component or execute any method in the parent component during any event execution of the child component. Since in Angular 2.0 the components are the core objects of the Angular framework, it is a very common concern for all of us regarding how we can pass the data or event into the parent component so that we can dynamically manipulate or configure the parent component while any changes are being done in the child component. In the world of web development, static components will not fulfill all our requirements, due to which we need to develop dynamic components or nonstatic components, which can take data from its parent component and also return some data or event to the parent component.

As I had already mentioned in my previous article, Angular 2.0 is actually made up a nested or hierarchical component structures, it means Angular 2.0 basically begins with a root component, which contains all the child components of the applications. The components act as a self contained entity because normally we want to encapsulate our component variables and functions, and we never want that other code to arbitrarily reach our code or value to check what changes can be done in the component. This architecture works fine for simply displaying data, but in the real world application, the data needs to flow both ways – i.e. back to the hierarchy – such as when the user makes changes to any data in the child component. In that case we need to tell the parent component about the changes, so the parent component updates its model and returns that data to the Server. Now, Angular 2 uses a different mechanism to send back data to the parent's events.

Now, whenever any action occurs within a child component, the child component fires an event which is traced by the parent component to intimate parent component. The parent component can perform separate actions against that event to perform its own logical operations.

If the child component wants to send the information back to its container; i.e., parent component, it can raise an event with the help of @Output decorator. Like the @Input decorator, we can always use @Output decorator to decorate any property of the child component. This property must be an event of the child component. The data to pass is called the event payload. In Angular 2, an event is defined with an EventEmitter object. Below is the sample example of an output event emitter property.

  1. @Output() click EventEmitter<string> = new EventEmitter<string>(); 
EventEmitter objects always accept any number of generic arguments. EventEmitter is an Angular2 abstraction and its only purpose is to emit the events in the components.

To declare output property, we need to first import the output and EventEmitter command from Angular Core module and then use @Output decorator to declare that property. 

To demonstrate this output property, we will develop an email registration form. For this, please perform the steps given below.
Step 1  

We create a typescript file named app.component.emailboxevent.ts and write down the code given below.
  1. import { Component, Input, Output, EventEmitter } from '@angular/core';  
  3. @Component({  
  4.     selector 'emailboxevent',  
  5.     template '<input  placeholder="{{email}}" #emailbox/><button class="red" (click)="register(emailbox)">Register</button>',  
  6.     styles [".red {colorred;}"]  
  7. })  
  9. export class EmailBoxEventComponent {  
  10.     @Input('placeholder')  
  11.     email string = "Type your email..";  
  12.      @Output() emailregister EventEmitter<string> = new EventEmitter<string>();  
  14.     register(txtEmail) {  
  15.         console.log('Email Address resgister properly...');  
  16.         if (txtEmail.value == '') {  
  17.             alert('Put your email address first..');  
  18.             return;  
  19.         }  
  20.         else {  
  21.              this.emailregister.emit(txtEmail.value);  
  22.         }  
  23.     }  

Step 2 
Now, add another typescript file named app.component.parent.ts and add the code given below.
  1. //components files  
  2. import { Component, OnInit } from '@angular/core';  
  3. //  
  5. @Component({  
  6.     moduleId,  
  7.     selector 'myapp',  
  8.     templateUrl 'app.component.parent.html',  
  9. })  
  11. export class ParentComponent implements OnInit {  
  12.     constructor() { }  
  14.     ngOnInit() { }  
  16.     confirmregister(email string) void {  
  17.         alert("Register Email Address is " + email);  
  18.     }  

Step 3
Now, add HTML file named app.component.parent.html and write down the code given below in the file.
  1. <div>  
  2.     <br />  
  3.     <h2>Email Register control with Events</h2>  
  4.     <emailboxevent [placeholder]="'Put your email'" (emailregister)="confirmregister($event)"></emailboxevent><br />  
  5. </div> 
Step 4 

Now, add a style sheet file named style.css and add css codes given below in the files
  1. .red {  
  2.     color black;  
  3.     backgroundcolor red;  
  4.     fontsizesmall;  
  5.     fontweightbold;  
  6. }  
  8. .blue {  
  9.     color white;  
  10.     backgroundcolor blue;  
  11.     fontsizesmall;  
  12.     fontweightbold;  
  13.     fontfamily'Franklin Gothic Medium''Arial Narrow', Arial, sansserif;  
  14.     fontstyleitalic;  

Step 5

Now, add another typescript file named app.module.ts and add the code given below.
  1. import { NgModule } from '@angular/core';  
  2. import { BrowserModule } from '@angular/platformbrowser';  
  3. import { ParentComponent } from './src/app.component.parent';  
  4. import { EmailBoxEventComponent } from './src/app.component.emailboxevent';  
  7. @NgModule({  
  8.     imports [BrowserModule],  
  9.     declarations [ParentComponent,  EmailBoxEventComponent],  
  10.     bootstrap [ParentComponent]  
  11. })  
  12. export class AppModule { } 
Step 6

Now, add another HTML file named index.html and add the code given below.
  1. <!DOCTYPE html>  
  2. <html>  
  3.   <head>  
  4.     <title>Angular2</title>  
  5.     <meta charset="UTF8">  
  6.     <meta name="viewport" content="width=devicewidth, initialscale=1">  
  7.     <link rel="stylesheet" href="../styles.css">  
  9.     <! Polyfill(s) for older browsers >  
  10.     <script src="../node_modules/corejs/client/shim.min.js"></script>  
  11.     <script src="../node_modules/zone.js/dist/zone.js"></script>  
  12.     <script src="../node_modules/reflectmetadata/Reflect.js"></script>  
  13.     <script src="../node_modules/systemjs/dist/system.src.js"></script>  
  15.     <script src="../systemjs.config.js"></script>  
  16.     <script>  
  17.       System.import('app').catch(function(err){ console.error(err); });  
  18.     </script>  
  19.   </head>  
  21.   <body>  
  22.     <myapp>Loading...</myapp>  
  23.   </body>  
  24. </html> 
Now, run the code in the browser and the output is as shown below. When we put an email address in the box and clicked on the register button. The child component emits the event to the parent with the given email value, which will be visible in an alert window.

Similar Articles