Delegation: EventEmitter or Observable in Angular

Cover Image for Delegation: EventEmitter or Observable in Angular
Matheus Mello
Matheus Mello
published a few days ago. updated a few hours ago

Delegation: EventEmitter or Observable in Angular? 🤔

Are you trying to implement a delegation pattern in your Angular project? Do you want to emit an event from one component and handle it in another component? 🚀🔗

Well, you've come to the right place! In this blog post, we'll explore two common approaches for achieving this: using EventEmitter or Observable. We'll address the common issues people encounter and provide easy solutions for them. 💡🛠️

The Setup 🖥️

Let's set the context: you have a Navigation component and an ObservingComponent. When the user clicks on a nav-item in the Navigation component, you want to emit an event and handle it in the ObservingComponent. Easy enough, right?

Here's how your code might look:

import { Component, Output, EventEmitter } from 'angular/core';

@Component({
  // other properties left out for brevity
  template: `
    <div class="nav-item" (click)="selectedNavItem(1)"></div>
  `
})
export class Navigation {
  @Output() navchange: EventEmitter<number> = new EventEmitter();

  selectedNavItem(item: number) {
    console.log(`selected nav item ${item}`);
    this.navchange.emit(item);
  }
}
export class ObservingComponent {
  // How do I observe the event?
  // <----------Observe/Register Event?-------->

  selectedNavItem(item: number) {
    console.log('item index changed!');
  }
}

Approach 1: Using EventEmitter ⚡💡

In Angular, EventEmitter is a powerful tool for communication between components. To make the ObservingComponent listen for the event emitted by the Navigation component, follow these steps:

  1. Import the EventEmitter and Output decorators from @angular/core in the ObservingComponent:

import { Component, EventEmitter, Output } from '@angular/core';
  1. Decorate a method with the @Output decorator in the Navigation component:

@Output() navchange: EventEmitter<number> = new EventEmitter();
  1. Emit the event in the selectedNavItem method of the Navigation component:

this.navchange.emit(item);
  1. In the ObservingComponent, create an instance of the Navigation component and subscribe to the navchange event:

import { Navigation } from './navigation.component';

export class ObservingComponent {
  navigationComponent = new Navigation();

  ngOnInit() {
    this.navigationComponent.navchange.subscribe((item: number) => {
      this.selectedNavItem(item);
    });
  }

  selectedNavItem(item: number) {
    console.log('item index changed!');
  }
}

With this approach, you can observe the event emitted by the Navigation component in the ObservingComponent using EventEmitter. 🎉🙌

Approach 2: Using Observable 🌈🔭

Alternatively, you can use the power of RxJS Observables to handle the event delegation. Here's how to do it:

  1. Import the necessary operators and the Subject class from rxjs/Rx in the Navigation component:

import { Subject } from 'rxjs/Subject';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/share';
  1. Replace the EventEmitter with a Subject in the Navigation component:

export class Navigation {
  private navchangeSubject: Subject<number> = new Subject();
  navchange = this.navchangeSubject.asObservable();

  selectedNavItem(item: number) {
    console.log(`selected nav item ${item}`);
    this.navchangeSubject.next(item);
  }
}
  1. In the ObservingComponent, create an instance of the Navigation component and subscribe to the navchange observable:

import { Navigation } from './navigation.component';

export class ObservingComponent {
  navigationComponent = new Navigation();

  ngOnInit() {
    this.navigationComponent.navchange.subscribe((item: number) => {
      this.selectedNavItem(item);
    });
  }

  selectedNavItem(item: number) {
    console.log('item index changed!');
  }
}

By using RxJS Observables, you have more flexibility and additional operators available for performing complex event handling. 🙌🔥

Choose Your Approach 👩‍💻👨‍💻

Now that you have two possible approaches for event delegation in Angular - using EventEmitter or Observable - it's time to choose the one that suits your project and requirements.

If you prefer a simpler, lightweight solution, go with EventEmitter. On the other hand, if you need more flexibility and sophisticated event handling, give Observable a try.

So, which approach are you going to use in your Angular project? Let us know in the comments below! 😄👇

Conclusion 📝✅

Delegation in Angular doesn't have to be complicated. By using either EventEmitter or Observable, you can easily emit events from one component and handle them in another component.

In this blog post, we covered both approaches, provided step-by-step instructions, and explained the benefits of each approach. Now it's time for you to implement delegation in your Angular project with confidence! 💪🚀

If you have any questions or additional tips, don't hesitate to leave a comment below. Happy delegating! 🎉🙌

📣 Did you find this blog post helpful? Share it with your fellow developers and spread the knowledge! 🤝🔗


More Stories

Cover Image for How can I echo a newline in a batch file?

How can I echo a newline in a batch file?

updated a few hours ago
batch-filenewlinewindows

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Matheus Mello
Matheus Mello
Cover Image for How do I run Redis on Windows?

How do I run Redis on Windows?

updated a few hours ago
rediswindows

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Matheus Mello
Matheus Mello
Cover Image for Best way to strip punctuation from a string

Best way to strip punctuation from a string

updated a few hours ago
punctuationpythonstring

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Matheus Mello
Matheus Mello
Cover Image for Purge or recreate a Ruby on Rails database

Purge or recreate a Ruby on Rails database

updated a few hours ago
rakeruby-on-railsruby-on-rails-3

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my

Matheus Mello
Matheus Mello