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

后端 未结 4 1339
执念已碎
执念已碎 2021-01-03 09:47

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 insi

4条回答
  •  悲哀的现实
    2021-01-03 10:01

    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

提交回复
热议问题