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:
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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With