How to use an EventEmitter with Angular?

Sometimes, we want to use an EventEmitter with Angular.

In this article, we’ll look at how to use an EventEmitter with Angular.

How to use an EventEmitter with Angular?

To use an EventEmitter with Angular, we can use it to emit an event from the child component to the parent.

For instance, we write

@Component({
  selector: "child",
  template: ` <button (click)="sendNotification()">Notify my parent!</button> `,
})
class Child {
  @Output() notifyParent: EventEmitter<any> = new EventEmitter();

  sendNotification() {
    this.notifyParent.emit("hello parent");
  }
}

to create the notifyParent EventEmitter object.

Then we call notifyParent.emit in the sendNotification method that’s called when we click the button.

Then in the parent component, we write

@Component({
  selector: "parent",
  template: ` <child (notifyParent)="getNotification($event)"></child> `,
})
class Parent {
  getNotification(evt) {
    // Do something with the notification (evt) sent by the child!
  }
}

to listen for the notifyParent event emitted by the child component.

And we get the argument we call emit with in getNotification.

Conclusion

To use an EventEmitter with Angular, we can use it to emit an event from the child component to the parent.