Run an angular 2 component method from JavaScript outside the component

1,358 views
Skip to first unread message

Ofer Gal

unread,
May 18, 2016, 12:09:13 PM5/18/16
to AngularJS
I have a component with this class:
export class AppComponent {
    show: boolean = false;
    toggele(){
         alert("Button Pushed");
        this.show = !this.show;
    }

how do I call toggel(); from a another JavaScript function not in the component?
How do I make my component accessible to the global scope?

Sander Elias

unread,
May 18, 2016, 11:25:16 PM5/18/16
to AngularJS
Hi Ofer,

To call toggel, get a reference to the dom element your components is on, then call the event that calls your function. In your case it's probably something like:

let ev = new MouseEvent('click',options)
document.querySelector('main-app').dispatchEvent(ev)

To answer your second question, you don't. Making components accessible to the global scope is a terrible idea. (google for 'why is global scope considered bad). There is probably a technical way to do that, but just don't go there.

Regards
Sander

Reply all
Reply to author
Forward
0 new messages