Cover image for EventEmitter in Angular Rxjs

EventEmitter in Angular Rxjs

muhammadawaisshaikh profile image Muhammad Awais ・1 min read

Angular provides an EventEmitter class that is used when publishing values from a component through the @Output() decorator.

EventEmitter extends RxJS Subject, adding an emit() method so it can send arbitrary values. When you call emit(), it passes the emitted value to the next() method of any subscribed observer.

Real life example for using EventEmitter is like a side-menu change detection on any event (click/onChange etc) from homepage performed.

let's have some hands-on at EventEmitter:

in side-menu ts we have to create an output decorator having with EventEmitter, and one boolean variable to have an boolean state of close/open, then after we have to create a method that will change the state of boolean variable, and also emit that boolean value, so that the updated value will be going towards parent component, which is home.

// side-menu.component.ts

@Output() toggle = new EventEmitter<any>();
visible: boolean = false;

onToggle() {
    this.visible = !this.visible;
    console.log("from side-menu", this.visible);
<!-- side-menu.component.html -->

<a (click)="onToggle()">Menu</a>

        <a href="#">Home</a>
        <a  href="#">About</a>

So, in home component view we have to call the side-menu child component and add the output decorator named toggle that we have created above in side-menu.component.ts

<!-- home.component.html -->

<app-side-menu (toggle)="menuToggle($event)"></app-side-menu>

Whenever, toggle output decorator emits from side-menu.component.ts, menuToggle method will be called

// home.component.ts

menuToggle(event) {
    console.log("from home", event);

That's it, :)

Posted on by:

muhammadawaisshaikh profile

Muhammad Awais


ReactJS | Angular | JavaScript | NodeJS| Ruby on Rails | Heroku | AWS


Editor guide