DEV Community

Cover image for EventEmitter in Angular Rxjs
Muhammad Awais
Muhammad Awais

Posted on

6 2

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, :)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay