Home > Net >  Call function from browser console in Angular
Call function from browser console in Angular

Time:12-31

I have a function inside an Angular component,lets say:

setDevMode(mode:string):void {
    this.devMode = mode;
}

How would I go about running it from the browser console?

CodePudding user response:

If this function is inside a closure, Then you can't call from the console.

Otherwise, you just do functionName(); and hit return.

CodePudding user response:

To call a method from a component instance, you need to get a reference to the component instance. You can do that in Angular 9 with the ng global variable, by using its getComponent function.

In order to use this, you need to have access to the html element created by your component instance. You can find it in the Elements tab in Chrome ("Inspector" in firefox), right click on the element and choose "Store as global variable" ("Use in console" in firefox). You now have a variable in the console that you can send to the getComponent function, for example temp1:

const myCompInstance = ng.getComponent(temp1)

component With this, you can now call the method like this:

myCompInstance.setDevMode("some_mode")

Notice that you will probably have to run ng.applyChanges on the element to see the UI update, like this:

ng.applyChanges(temp1)
  • Related