Blog>
Snippets

Communicating with Angular Elements via Custom Events

Showcase how an Angular Element can dispatch custom events and how to listen and respond to these events within a non-Angular parent application, such as plain JavaScript or JQuery.
// In the Angular component (child):
@Component({
  selector: 'app-custom-element',
  template: `<button (click)="handleClick()">Click Me!</button>`
})
export class CustomElement {
  @Output() myCustomEvent = new EventEmitter();

  handleClick() {
    // Emitting the custom event with some payload
    this.myCustomEvent.emit({ payload: 'Some data' });
  }
}
This Angular snippet shows how to create a custom event using EventEmitter and how to dispatch it from an Angular component when, for example, a button within the component template is clicked.
// In the parent application (plain JavaScript):

// Function to handle the custom event
function handleMyCustomEvent(event) {
  // Accessing the payload
  let data = event.detail;
  console.log('Custom event received with data:', data.payload);
}

// Select the Angular element
const angularElement = document.querySelector('app-custom-element');

// Listen for the custom event from the Angular element
angularElement.addEventListener('myCustomEvent', handleMyCustomEvent);
This snippet demonstrates how a non-Angular parent application, such as a plain JavaScript app, can listen for custom events dispatched by an Angular element. Here, it selects the Angular element, listens for the 'myCustomEvent', and defines what to do when the event is received using the 'handleMyCustomEvent' function.
// In the parent application (JQuery):

// Function to handle the custom event
function handleMyCustomEvent(event) {
  // Accessing the payload
  let data = event.detail;
  console.log('Custom event received with data:', data.payload);
}

// Listen for the custom event from the Angular element using JQuery
$( 'app-custom-element' ).on('myCustomEvent', handleMyCustomEvent);
This is a JQuery equivalent of the previous snippet. It demonstrates how to use JQuery to listen for custom events from an Angular component. The event is handled by the same 'handleMyCustomEvent' function as defined previously.