You are on page 1of 11

Browser Events

and
Custom Events

Angular
Angular-Custom Events
• Using the built-in events in Angular works like data
binding.
• By wrapping an event name in (), you let Angular
know what event you’re binding to.
• The event is binded to an event handler which can be
used to manipulate the data.
• The following is an example of the syntax for a built-
in event:
• <input type="text"
(change)="eventHandler($event)" />
Angular-Custom Events
Angular-Custom Events
• Custom Events are useful when transmitting data
from a child component to a parent component.
• EventEmitter class is used to raise an event by
the child component.
• The event carries the data from the child component.
• In the parent view the embedded child component
invokes the method of the parent component class in
response to the raised event.
• The data is passed to the invoked method.
app.component.html child.component.html

<app-child
(event)="parentHandler($event)"> Click
</app-child>

3 1

app.component.ts
child.component.ts
@Output() event

parentHandler(data:type){ 2
onClick(){
} raise event
}
Angular-Custom Events
• @Output() marks a property in a
child component as a doorway
through which data can travel from
the child to the parent.
• The child component uses the
@Output() property to raise an
event to notify the parent of the
change.
• To raise an event, an @Output()
must have the type of EventEmitter,
which is a class in @angular/core
that you use to emit custom events.
Angular-Custom Events

• (newMessageEvent)="addMessage($event)", The event


binding connects the event in the child, newMessageEvent, to
the method in the parent, addMessage($event).
• The $event contains the data that the user types into the
<input> in the child template UI.
Angular-Custom Events
Data transfer from Parent to Child
• @Input() decorator can be used to direct data
from the parent component to the child component.
• A property in the child component is decorated with
@Input()
• When the chils component is placed in the parent
template, this @Input() declared property is
binded with the property of the parent.
app.component.html child.component.html

<app-child [cProp]="pProp">
3
</app-child>

1
2
app.component.ts
child.component.ts

pProp : type @Input() cProp:type

You might also like