简体   繁体   English

从 Angular 中的浏览器控制台调用 function

[英]Call function from browser console in Angular

I have a function inside an Angular component,lets say:我在 Angular 组件中有一个 function,可以说:

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

How would I go about running it from the browser console?我将如何 go 从浏览器控制台运行它?

If this function is inside a closure, Then you can't call from the console.如果此 function 在闭包内,则无法从控制台调用。

Otherwise, you just do functionName();否则,您只需执行functionName(); and hit return.并点击返回。

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.您可以在 Angular 9+ 中使用ng全局变量执行此操作,方法是使用其getComponent function。

In order to use this, you need to have access to the html element created by your component instance.为了使用它,您需要访问由您的组件实例创建的 html 元素。 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).您可以在 Chrome 的 Elements 选项卡中找到它(firefox 中的“Inspector”),右键单击该元素并选择“Store as global variable”(firefox 中的“Use in console”)。 You now have a variable in the console that you can send to the getComponent function, for example temp1 :您现在在控制台中有一个变量,您可以将其发送到getComponent function,例如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才能看到 UI 更新,如下所示:

ng.applyChanges(temp1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM