DEV Community

Cover image for EventEmitter in Angular Rxjs
Muhammad Awais
Muhammad Awais

Posted on

EventEmitter in Angular Rxjs

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;
    this.toggle.emit(this.visible);
    console.log("from side-menu", this.visible);
  }
Enter fullscreen mode Exit fullscreen mode
<!-- side-menu.component.html -->

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

<ul>
    <li>
        <a href="#">Home</a>
    </li>
    <li>
        <a  href="#">About</a>
    </li>
</ul>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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);
  }
Enter fullscreen mode Exit fullscreen mode

That's it, :)

Top comments (0)