Search⌘ K
AI Features

Event Listening and Updates in Angular

Explore how Angular listens to domain events raised by a Vue front-end within a micro front-end architecture. Learn to manage event subscriptions, update component states, and use ChangeDetectorRef to trigger Angular's change detection manually, ensuring the UI updates correctly in response to external events.

The only remaining thing to do in our Angular application is to listen to any domain events that are raised from our Vue front-end. Again, we will need to use the declaration files for our micro-event-bus library by importing them through npm as follows:

npm link micro-event-bus

Here, we are importing the type definitions for our micro-event-bus library into our Angular application. We can now listen to events by updating our angular-app/src/app/app.component.ts file as follows:

TypeScript 4.9.5
import { MicroEventBus } from 'micro-event-bus';
export let microEventBus: MicroEventBus =
(window as any).microEventBus;
export class AppComponent {
// Existing class member variables
constructor(
broadCastService: AngularBroadcastService,
private scriptLoaderService: ScriptLoaderService,
private cd: ChangeDetectorRef
) {
_.bindAll(this, [
"onLoginClicked",
"onLoginEvent",
"toggleCheckoutOnly",
"toggleContinueShopping",
"togglePlaceOrder"
]);
// Internal broadcast event listeners
microEventBus.on("checking-out")
.subscribe(this.toggleCheckoutOnly);
microEventBus.on("continue-shopping")
.subscribe(this.toggleContinueShopping);
microEventBus.on("place-order")
.subscribe(this.togglePlaceOrder);
}
// Existing functions
toggleCheckoutOnly() {
this.shoppingCartStyles = "split";
this.hideProducts = true;
this.cd.detectChanges();
}
toggleContinueShopping() {
this.shoppingCartStyles = "split right";
this.hideProducts = false;
this.cd.detectChanges();
}
togglePlaceOrder() {
this.hideShoppingCartRegion = true;
this.hideProducts = true;
this.hideOrderPlaced = false;
this.cd.detectChanges();
}
}
...