5

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?

2 Answers2

6

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)

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)
ShamPooSham
  • 2,301
  • 2
  • 19
  • 28
1

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

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

  • Sorry, I should have made more clear that the function is inside an angular component instance. – gabrielsalvador Dec 31 '21 at 12:13
  • @gabrielsalvador "functions" inside classes are usually called methods, they aren't referred to as functions since they are bound to the instance of the class they're in and are used to change the state of that instance. That said, you should be able to get the component instance with `ng.getComponent(*htmlElement*)`. With that instance, you can call the methods. https://angular.io/api/core/global/ngGetComponent – ShamPooSham Dec 31 '21 at 12:18
  • this solved it, thank you for the clarification. I've marked your answer as correct, please update it with the specifics for angular – gabrielsalvador Dec 31 '21 at 12:32
  • @gabrielsalvador I created a new answer since I wasn't the author of this answer. Could you mark that one as accepted instead? – ShamPooSham Dec 31 '21 at 12:40