"EventEmitter" is used in Angular, starting from version 2 and later.
In Angular, EventEmitter
is a class provided by the @angular/core
module, and it is used to create custom events that can be emitted from components and listened to by other components. It plays a crucial role in the parent-child communication or component interaction within an Angular application.
Here's how you can use EventEmitter
in Angular:
-
Import EventEmitter: You need to import
EventEmitter
from@angular/core
at the beginning of your component file where you want to use it.
import { EventEmitter } from '@angular/core';
-
Declare an EventEmitter Property: Inside your component class, you declare an
EventEmitter
property. You can specify the event type as a generic parameter, indicating what kind of data the event will emit.
myEvent = new EventEmitter<string>();
-
Emitting an Event: To emit an event, you can call the
emit
method on yourEventEmitter
instance and pass the data you want to emit. For example:
this.myEvent.emit('Data to send to other components');
-
Listening to the Event: In another component or the parent component, you can subscribe to the event using the
(eventEmitterName)
syntax in the component's template. For example:
<app-child (myEvent)="handleEvent($event)"></app-child>
Here, when the "myEvent" event is emitted in the app-child
component, the handleEvent
method in the parent component will be called with the emitted data.
-
Handling the Event: In the parent or listening component, you define a method that will be executed when the event is emitted. In the example above,
handleEvent($event)
is the method that handles the emitted event. You can access the emitted data via the$event
parameter.
By using EventEmitter
, you can establish communication between components in your Angular application, enabling parent-child or custom component interaction. It's a way to implement a publish-subscribe mechanism within your application, allowing components to notify and react to events without direct coupling.
Top comments (0)