从另一个模块访问 Angular 2 个组件/window
Access Angular 2 component from another module / window
我希望从另一个模块访问 Angular 2 组件以及 window 对象。 window 对象仅用于在浏览器控制台中播放而不实际用于生产(仅供参考)。我在想我可以 'export default class MyComponent' 但这似乎不起作用。我如何从另一个模块/window?
访问实例化的 MyAppComponent class
<body>
<my-app></my-app>
<script>
System.import('ang').then(function (ang) {
window.ang = ang;
});
</script>
</body>
...
import {Component, View, bootstrap} from 'angular2/angular2';
@Component({
selector: 'my-app'
})
@View({
template: `<h1>Hello {{ count }}</h1><br>`
})
class MyAppComponent {
public count: number;
constructor() {
this.count = 0;
}
public increment(): void {
this.count++;
}
}
bootstrap(MyAppComponent);
然后想做这样的事情:
ang.increment();
您可以通过 bootstrap 回调:
bootstrap(AppComponent, [
ROUTER_PROVIDERS,
]).then((app)=> {
window.app = app
});
然后从控制台调用
app.instance.myMethod()
这是另一个解决方案,它利用了一些 Angular 内部结构。我可以验证这在 Angular 6 中有效,但当然要注意 YMMV。
同样一文不值,TypeScript 对此不太满意,所以在我的代码中,我不得不到处投射东西。为了代码清晰,我在这里删除了强制转换。
const debugElement: DebugElement = window.ng.probe(document.querySelector('my-app'))
const app: MyAppComponent = debugElement.componentInstance;
app.increment();
使您的组件成为全局变量
constructor() {
window['AppComponent'] = {Appcomponent: {all:this}};
}
示例:https://stackblitz.com/edit/angular-xjaaen
我希望从另一个模块访问 Angular 2 组件以及 window 对象。 window 对象仅用于在浏览器控制台中播放而不实际用于生产(仅供参考)。我在想我可以 'export default class MyComponent' 但这似乎不起作用。我如何从另一个模块/window?
访问实例化的 MyAppComponent class<body>
<my-app></my-app>
<script>
System.import('ang').then(function (ang) {
window.ang = ang;
});
</script>
</body>
...
import {Component, View, bootstrap} from 'angular2/angular2';
@Component({
selector: 'my-app'
})
@View({
template: `<h1>Hello {{ count }}</h1><br>`
})
class MyAppComponent {
public count: number;
constructor() {
this.count = 0;
}
public increment(): void {
this.count++;
}
}
bootstrap(MyAppComponent);
然后想做这样的事情:
ang.increment();
您可以通过 bootstrap 回调:
bootstrap(AppComponent, [
ROUTER_PROVIDERS,
]).then((app)=> {
window.app = app
});
然后从控制台调用
app.instance.myMethod()
这是另一个解决方案,它利用了一些 Angular 内部结构。我可以验证这在 Angular 6 中有效,但当然要注意 YMMV。
同样一文不值,TypeScript 对此不太满意,所以在我的代码中,我不得不到处投射东西。为了代码清晰,我在这里删除了强制转换。
const debugElement: DebugElement = window.ng.probe(document.querySelector('my-app'))
const app: MyAppComponent = debugElement.componentInstance;
app.increment();
使您的组件成为全局变量
constructor() {
window['AppComponent'] = {Appcomponent: {all:this}};
}
示例:https://stackblitz.com/edit/angular-xjaaen