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?
The way it should be done depends on particular case, especially on the precedence.
If Silverlight aplication is initialized before Angular application, and
window.somePlainJsFunction
is called before finishing Angular application initialization, this will result in race condition. Even if there was an acceptable way to get Angular provider instance externally, the instance wouldn't exist duringsomePlainJsFunction
call.If
window.somePlainJsFunction
callback is called after Angular bootstrap,window.somePlainJsFunction
should be assigned inside Angular application, whereSomeAngularClass
provider instance is reachable:If
window.somePlainJsFunction
callback is called before Angular bootstrap, it should provide global data for Angular application to pick up:Then
window.angularGlobalData
can be used inside Angular, either directly or as a provider.Working Example
I think this is what you are looking for service out side angular
You can create function/class outside Angular and provide as a value in the angular. in this way you can handle both angular and non angular stuffs together:
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:
Then you can all 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:
This code you can add in any component. I have added it to my root component - AppComponent
You can use a events, so you have the JavaScript send an event that you are listening for in your service.
The CustomEvent is a new feature so you might need to polyfill it: https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent
JavaScript:
Angular: