dinsdag 6 februari 2024

Call Angular method from Javascript

There are situations in which your context becomes javascript and you
need to get back to the Angular context.

Do this with a CustomEvent.

In Javascript do:
function (theDetails){
	var event = new CustomEvent("uniquenamefor.thecustomevent", { 
       detail: theDetails, bubbles: true, cancelable: true
    });    
    window.dispatchEvent(event);
}

This event will be send in the webbrower and we need Anuglar to pick it up.

In Angular do:
import { HostListener, Component } from '@angular/core';

    @HostListener('window:uniquenamefor.thecustomevent', ['$event']) 
    async onUniqueCustomEvent(event) {
    	alert(event.detail);
    }
    
The Angular framework only allows HostListeners on components/directives, so
if you want to catch the CustomEvent in a service you need to resort back
to good old Javascript:
   window.addEventListener('uniquenamefor.thecustomevent', 
       this.onUniqueCustomEvent.bind(this));

Geen opmerkingen:

Een reactie posten