Angular 2 @Input and @Output Example

@Input

@Output

@Input

@Output

@Input(alias)

@Output(alias)

@Input

@Output

@Input

@Output

EventEmitter

Software Used

@Input

@Input

@Input

@Input(alias)

@Input

@Input() ctMsg : string;

@Input

ctArray

@Input('ctArray') myctArray : Array<string>

@Input

@Input('stdLeader') myStdLeader : Student;

@Output

@Output

@Output

EventEmitter

@Output

@Output(alias)

@Output

@Output('addStudentEvent') addStdEvent = new EventEmitter<Student>();

addStudentEvent

@Output

@Output() sendMsgEvent = new EventEmitter<string>();

sendMsgEvent

Aliasing Input and Output properties

@Input

@Output

@Input

@Output

@Input(alias)

<child-two [stdLeader] = "stdLeaderObj"> </child-two>

stdLeaderObj

stdLeader

@Input('stdLeader') myStdLeader : Student;

stdLeader

myStdLeader

@Output(alias)

<child-two (addNumberEvent) = "printSum($event)" > </child-two>

addNumberEvent

printSum()

@Output('addNumberEvent') addNumEvent = new EventEmitter<number>();

addNumberEvent

addNumEvent

Component Property Binding using @Input

@Input

Student

stdLeaderObj = new Student('Narendra', 'Modi');

<child-two [stdLeader] = "stdLeaderObj"> </child-two>

@Input

@Input('stdLeader') myStdLeader : Student;

{{myStdLeader.fname +' '+ myStdLeader.lname}}

Custom Event Binding using @Output and EventEmitter

@Output

input

$event.target.value

<div> First Number :<input (input)="num1=$event.target.value" /> <br/> Second Number:<input (input)="num2=$event.target.value" /> <br/> <br/> <button (click)="addNumber()">Add Number</button> </div>

click

emit()

EventEmitter

addNumber() { this.addNumEvent.emit(parseInt(this.num1) + parseInt(this.num2)); }

EventEmitter

@Output

@Output('addNumberEvent') addNumEvent = new EventEmitter<number>();

addNumberEvent

emit()

$event

<child-two (addNumberEvent) = "printSum($event)" > </child-two>

addNumberEvent

printSum()

printSum(res) { this.sum = res; }

Complete Example using TypeScript

@Input

@Output

@Input

@Output

export class Student { constructor(public fname?: string, public lname?: string) { } }

?

?

Student

Student

new Student()

?

new Student()

import {Component} from '@angular/core'; import {Student} from './student'; @Component({ selector: 'input-output', template: ` <h1>{{parentTitle}}</h1> <child-one [ctMsg]="cityMsg" [ctArray]="cityArray" [studentAddMsg]="stdAddMsg" (addStudentEvent) = "saveData($event)" (sendMsgEvent) = "printMsg($event)" > </child-one> <p>Name: {{stdFullName}}</p> <p>Message: {{msg}}</p> <child-two [studentMsg] = "stdMsg" [stdLeader] = "stdLeaderObj" (addNumberEvent) = "printSum($event)" > </child-two> <p>Sum: {{sum}}</p> ` }) export class ParentComponent { parentTitle = 'Parent Component'; //Property for child component one cityMsg = 'Indian City Names'; cityArray = ['Varanasi', 'Delhi', 'Mumbai']; stdAddMsg = 'Add Student'; //Property for child component two stdMsg = 'Student Leader Detail'; stdLeaderObj = new Student('Narendra', 'Modi'); //Property used in parent stdFullName = ''; sum = ''; msg = ''; saveData(std) { this.stdFullName = std.fname + ' ' + std.lname ; } printSum(res) { this.sum = res; } printMsg(msg) { this.msg = msg; } }

import {Component, EventEmitter, Input, Output} from '@angular/core'; import {Student} from './student'; @Component({ selector: 'child-one', template: ` <h3>{{childTitle}}</h3> <b> {{ctMsg}}</b> <ul> <li *ngFor = "let cname of myctArray"> {{cname}} </li> </ul> <b>{{addMsg}}</b><br/> <div> First Name:<input (input)="student.fname=$event.target.value" /> <br/> Last Name:<input (input)="student.lname=$event.target.value" /> <br/> <button (click)="addStudent()">Add Student</button> </div> <br/><b>{{message}}</b><br/> <div> Message :<input (input)="msg=$event.target.value" /> <br/> <button (click)="sendMsg()">Send</button> </div> ` }) export class ChildOneComponent { @Input() ctMsg : string; @Input('ctArray') myctArray : Array<string> @Input('studentAddMsg') addMsg : string; @Output('addStudentEvent') addStdEvent = new EventEmitter<Student>(); @Output() sendMsgEvent = new EventEmitter<string>(); student = new Student(); childTitle = '---Child One---'; message = 'Send Message' msg : string; addStudent() { this.addStdEvent.emit(this.student); } sendMsg() { this.sendMsgEvent.emit(this.msg); } }

import {Component, EventEmitter, Input, Output} from '@angular/core'; import {Student} from './student'; @Component({ selector: 'child-two', template: ` <h3>{{childTitle}}</h3> <p> {{studentMsg}} : {{myStdLeader.fname +' '+ myStdLeader.lname}} </p> <b>{{addNumMsg}}</b><br/> <div> First Number :<input (input)="num1=$event.target.value" /> <br/> Second Number:<input (input)="num2=$event.target.value" /> <br/> <br/> <button (click)="addNumber()">Add Number</button> </div> ` }) export class ChildTwoComponent { @Input() studentMsg : string; @Input('stdLeader') myStdLeader : Student; @Output('addNumberEvent') addNumEvent = new EventEmitter<number>(); childTitle = '---Child Two---'; addNumMsg ='Add Number' num1 : ''; num2 : ''; addNumber() { this.addNumEvent.emit(parseInt(this.num1) + parseInt(this.num2)); } }

import {NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {ParentComponent} from './parent.component'; import {ChildOneComponent} from './childone.component'; import {ChildTwoComponent} from './childtwo.component'; @NgModule({ imports: [BrowserModule], declarations: [ParentComponent, ChildOneComponent, ChildTwoComponent], bootstrap: [ParentComponent] }) export class AppModule { }

import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import {AppModule} from './module'; const platform = platformBrowserDynamic(); platform.bootstrapModule(AppModule);

<html> <head> <title>Angular 2 Demo</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="node_modules/core-js/client/shim.min.js"></script> <script src="node_modules/zone.js/dist/zone.js"></script> <script src="node_modules/reflect-metadata/Reflect.js"></script> <script src="node_modules/systemjs/dist/system.src.js"></script> <!-- Configure SystemJS --> <script src="systemjs.config.js"></script> <script> System.import('myApp').catch(function(err){ console.error(err); }); </script> </head> <body> <input-output>Please Wait...</input-output> </body> </html>

Run Application

References

Download Source Code

This page will walk through angular 2 @Input and @Output example. @Input is a decorator to mark an input property and @Output is a decorator to mark an output property.is used to define an input property to achieve component property binding.is used to define output property to achieve custom event binding.andcan define alias for property names asand. Here on this page we will provide a complete example ofanddecorators. We are creating a parent component and two child components. We will perform component property binding and custom event binding using both the child components. In our example we will usewith different data types such as string, number, array and user defined class.will be used with the instance of. Now find the complete example step by step.Find the software used in our demo.1. Angular 2.3.02. TypeScript 2.0.103. Node.js 4.6.04. NPM 3.10.85. Firefox 50.1.0decorator binds a property within one component (child component) to receive a value from another component (parent component). This is one way communication from parent to child. The component property should be annotated withdecorator to act as input property. A component can receive a value from another component using component property binding. Now we will see how to use. It can be annotated at any type of property such as number, string, array or user defined class. To use alias for the binding property name we need to assign an alias name asFind the use ofwith string data type.Now find array data type withdecorator. Here we are aliasing the property name. In the component property binding, alias namewill be used.Now finddecorator with a property of user defined class type.decorator binds a property of a component to send data from one component (child component) to calling component (parent component). This is one way communication from child to parent component.binds a property of the type of angularclass. This property name becomes custom event name for calling component.decorator can also alias the property name asand now this alias name will be used in custom event binding in calling component.Find thedecorator using aliasing.In the above code snippetwill become custom event name. Now finddecorator without aliasing.Herewill be custom event name.anddecorate input and output properties.can alias input property name andcan alias output property name.To alias input property use an alias as. Find code snippet.Here we are doing property binding.is the property of parent component.is the alias of child component property. Now find the below ode snippet.What we achieve thatis the alias ofproperty.To alias output property use alias as. Find the custom event binding as below.Hereis a custom event name. When this event will invoke,method will be executed. Now find the code snippet.What we achieve here is thatis the alias ofFind the steps for component property binding usingdecorator step by step.1. In the parent component, first create a property. Here we are creating a property of our classtype.2. Create a custom element in parent component that is a selector of one of our child component. Here we will perform component property binding.3. Usedecorator to declare child component property as an input property that will receive value from parent using component property binding. Here we are using aliasing for property name.4. Now we are ready to fetch values from input component property in our child component.Here we will discuss custom event binding usingdecorator step by step.1. Create text box using element property binding in child component.event is fired when there is any change in text box.fetches the current value of text box entered by user.2. Find the method created in child component that will be fired whenevent is invoked on click of button from above (step-1) code snippet.is the method ofclass that emits event payload.3. In the child component, create an instance ofannotated bydecorator. This instance will work as custom event name. Here we are using aliasing for custom event name.4. Now we are performing custom event binding. The custom eventwill be invoked in parent component whenmethod is invoked from child component. The event payload is accessed byobject.5. The eventwill callmethod.We will provide a complete example ofanddecorator using TypeScript. In our example we will create a parent component and two child component. Both child will useanddecorator.In the above code we will observe that we are using question markin constructor parameter. By using question markin constructor parameter, we achieve that while creating instance ofclass, passing arguments are optional. And it is possible to create instance of ourclass aswithout passing any argument. If we do not use question markin constructor parameters,will through error and requires arguments.Find the steps to run the example.1. Install Node.js and NPM in the system if not already installed. Make sure that Node.js version must be 4.x.x or higher and NPM version must be 3.x.x or higher.2. Download the source code using download link given below in the example.3. Go to the root folder of the project using command prompt and runcommand.4. Now runcommand.5. Now run index.html file. Find the print screen of the output.