Angular Custom Event Binding + EventEmitter Example

EventEmitter

EventEmitter

EventEmitter

@Output()

emit()

$event

Software Used

Steps for Custom Event Binding & Component Property Binding with Diagram

person.component.ts

app.component.ts

app.component.ts

person.component.ts

app.component.ts

person.component.ts

person-app

person-app

AppComponent

Student

studentObj

PersonComponent

student

Student

@Input

app.component.html

studentObj

AppComponent

student

PersonComponent

person-app

person.component.html

student

input

student

$event.target.value

student

PersonComponent

studentObj

AppComponent

student

studentObj

update()

PersonComponent

updateEmployee

EventEmitter

@Output

EventEmitter

emit()

updateEmployee.emit()

employee

app.component.html

updateEmployee

saveData()

AppComponent

$event

emit()

employee

studentObj

fullName

AppComponent

app.component.html

studentObj

student

student

EventEmitter

EventEmitter

emit()

EventEmitter

import {Component, EventEmitter, Input, Output} from '@angular/core';

@Output

@Output() updateEmployee = new EventEmitter<Employee>();

Employee

@Output()

updateEmployee

emit()

EventEmitter

Employee

this.updateEmployee.emit(this.employee);

emit()

$event

Create Custom Event

updateEmployee

EventEmitter

updateEmployee

@Output() updateEmployee = new EventEmitter<Employee>();

@Output

emit()

this.updateEmployee.emit(this.employee);

updateEmployee

<person-app (updateEmployee) ="saveData($event)" [student] ="studentObj"> </person-app>

updateEmployee

<person-app on-updateEmployee ="saveData($event)" [student] ="studentObj"> </person-app>

[student] ="studentObj"

Create a Sample Class

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

export class Employee { public fname: string; public lname: string; constructor() { } }

Student

Employee

Create Child Component with EventEmitter

import {Component, EventEmitter, Input, Output} from '@angular/core'; import {Student} from './student'; import {Employee} from './employee'; @Component({ selector: 'person-app', templateUrl: './person.component.html' }) export class PersonComponent { @Input() student : Student; @Output() updateEmployee = new EventEmitter<Employee>(); employee = new Employee(); update() { this.employee.fname = this.student.fname; this.employee.lname = this.student.lname; this.updateEmployee.emit(this.employee); } }

update()

emit()

update()

<div> <b>Id: {{student.id}} </b> <br/> <input [value]="student.fname" (input)="student.fname=$event.target.value" /> <br/> <input [value]="student.lname" (input)="student.lname=$event.target.value" /> <br/> <br/> <button (click)="update()">Update</button> </div>

input

$event.target.value

update()

click

Create Parent Component with Custom Event Binding

import {Component} from '@angular/core'; import {Student} from './student'; @Component({ selector: 'app-root', templateUrl: './app.component.html' }) export class AppComponent { title = 'Update Person'; fullName = ''; studentObj = new Student(100, 'Mahesh', 'Sharma'); saveData(emp) { this.fullName = emp.fname + ' ' + emp.lname ; } }

Student

saveData()

<h3>{{title}}</h3> <person-app (updateEmployee) ="saveData($event)" [student] ="studentObj"> </person-app> <p>{{studentObj.fname + ' '+ studentObj.lname}} </p> <p>{{fullName}}</p>

updateEmployee

EventEmitter

this.updateEmployee.emit(this.employee);

student

Create Module

import {NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {AppComponent} from './app.component'; import {PersonComponent} from './person.component'; @NgModule({ imports: [BrowserModule], declarations: [AppComponent, PersonComponent], bootstrap: [AppComponent] }) export class AppModule { }

Run Application

input

student

studentObj

update

emit()

updateEmployee

saveData()

References

Download Source Code

On this page we will provide Angular custom event binding andexample. Angular framework provides event binding using in-built event as well as custom event. Event binding is achieved using parenthesisandkeyword. When using parenthesis, we need to write our event name inside it. When usingkeyword,is added as prefix with event name. Custom events are theinstances. To create a custom event we need to create an instance ofannotated by. Then this instance callsmethod to emit payload which can be received by event object. In our example we are taking a parent child component communication example. In this example to send data from parent to child component, property binding will be used and to get data in parent component from child component, custom event binding will be used. Now we will discuss complete example step-by-step.Find the software used in our demo.1. Angular 9.1.112. Node.js 12.5.03. NPM 6.9.0Find the diagram for custom event binding and component property binding. Arrow incolor is showing flow of custom event binding and arrow incolor is showing flow of component property binding.We will observe that thearrow direction for custom event binding is fromtoand for component property bindingarrow direction is fromto. Find the steps involved in custom event binding and component property binding.1. In the above diagram we are performing parent child communication using custom event binding and component property binding.is behaving as parent andis behaving as child. The child selectorwill be used to create a custom element in parent component. Component property binding and custom event binding will take place inelement.2. Inwe are creating an object ofclass as. Inwe are creating an input variable asofclass type.decorator is used to mark a variable as input variable.3. Inwe are performing component property binding between the objectsofandofinelement.4. Inthe objectis providing its value to text box using element property binding.5. When user changes values in text box then onevent the values ofobject is getting changed. Here input event binding is taking place.returns current input value by user.6. In component property binding if the object sent to child is being updated then the reference object in parent will also get updated because they are pointing to the same object. So whenobject ofis getting updated then at the same timeofwill also get updated. It meansandboth objects are always in sync. In property binding it happens only in case of object of a class and not in case of primitive data type such string, number.7. On click of update button,method ofwill be called. Here click event binding is taking place.8. The objectof angularclass works as custom event binding name.decorator is used to mark a variable as output variable.hasmethod that emits the payload.9. The execution of codewill invoke custom event binding and will sendobject to custom event binding. Custom event is taking place in. Whenevent fires then it callsmethod ofcontains the payload sent bymethod that isobject.10. In the output we are printingandofusing interpolation in. Hereandobject will keep same values even afterobject changes by user update in text box.is a class in angular framework. It hasmethod that emits custom events. We can usein custom event binding. To achieve it first we need to import it in our component file as given below.And then initialize it usingdecorator as follows.Hereis our TypeScript class.defines an output variable.will be aname. Usingmethod ofclass we emitsobject to parent component in custom event binding as follows.The object emitted bymethod can be accessed using event objectSuppose we want to create a custom event named as. So first of all we need to instantiate an instance ofin the variableas below.We need to annotate it withthat declares it as output variable. Custom event binding is used in parent child component communication. Here we will send data from child component to parent component. To send data we need to usemethod as below.Now we are ready to use variableas custom event. Event binding can be done using parenthesisorkeyword. Find event binding usingNow we will usekeyword forevent binding.In the above code snippetis working as a property binding to send data from parent component to child component.For our demo we are creating two sample classes using TypeScript as follows.We will create the instance ofclass in our parent component and will send it to child component using component property binding. Then we will set data toclass instance in child component and will send it to parent component using custom event binding.Find child component file used in our example.: Defines input variable in component communication. It is used to communicate from parent to child component using property binding.: Defines output variable in component communication. It is used to communicate from child to parent component using custom event binding.In our component file we have created a methodthat will callmethod.method is being used in our HTML template as given below.In our HTML template we are binding student object with HTML elements using property binding. We are also using DOMevent binding to fetch current value entered by user and assigning it back to student instance. To access the current values entered by user we use. On the click of button,method will be called that is usingevent binding.Now we will create parent component that will use custom event binding. Find the component.Here we are creating an object ofclass. Methodwill be called in custom event binding. Find the HTML template used in our parent component.Look at the code, the variabledeclared in child component usingwill work as an event that is. The event will be executed when the below line of code will execute.The propertyin our HTML template binds the value to input variable in child component.To run the application, find the steps.Download source code using download link given below on this page.Use downloadedin your Angular CLI application. To install Angular CLI, find the link Runusing command prompt.Access the URLFind the print screen of the output.Here we are getting two output, first is because of component property binding and second is because of custom event binding.When we change first name and last name in text box then byevent theobject gets changed and because of component property binding it is the same object reference ofthat will also get changed.On click ofbuttonmethod of child component is called and hencemethod will execute that will generateevent in parent component and that will callmethod because of custom event binding.