Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call an Angular 4 method from a standalone plain JavaScript function?

I'd like to be able to pass some data\propagate events from a plugin on the page to my Angular 4 app.

More specifically, in my case data\events are generated inside a Silverlight plugin app that is next to the Angular app on the page.

I have the following solution in my mind:

  • Create a global JS function which gets called from Silverlight (since this seems to be the simplest way to get data out from Silverlight) when there is a need to talk to Angular side.
  • The function, in turn, calls some Angular class method passing data collected from Silverlight.

As an illustration to that (excluding the Silverlight part), we could have the following.

A method as an entry point on the Angular side:

export class SomeAngularClass {
    public method(data: any): void {
        ...
    }
}

And somewhere outside the Angular realm, we add a global plain JavaScript function (to be called by Silverlight):

window.somePlainJsFunction = function (data) {
    // How to consume SomeAngularClass.method() from here?
}

The question is: how can we call the Angular class methods from a plain JavaScript function?

like image 348
Alexander Abakumov Avatar asked Dec 05 '22 13:12

Alexander Abakumov


1 Answers

As pointed by @Dumpen, you can use @HostListener to get the custom event dispatched from javascript outside of Angular. If you also want to send parameters, then you can send them by adding them as detail object.

In Javascript:

function dispatch(email, password) {
    var event = new CustomEvent('onLogin', {
        detail: {
            email: email,
            password: password
        }
    })
    window.dispatchEvent(event);
}

Then you can call this method on button click.

Now to listen to this dispatched event in Angular, you can create function in Angular component and add @HostListener to it like below:

@HostListener('window:onLogin', ['$event.detail'])
onLogin(detail) {
    console.log('login', detail);
}

This code you can add in any component. I have added it to my root component - AppComponent

like image 149
Pranit More Avatar answered Dec 08 '22 03:12

Pranit More