从另一个模块/窗口访问Angular 2组件

5

我希望能够从另一个模块以及window对象中访问Angular 2组件。window对象仅用于在浏览器控制台中进行调试,而不是实际生产(供您参考)。我认为我可以使用“export default class MyComponent”,但似乎不起作用。如何从另一个模块/窗口中访问已实例化的MyAppComponent类?

<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();

我可以建议接受@Jeff Fairley的答案,它对我有用,适用于Angular 6。 - Arnaud P
3个回答

2

这里有另一种解决方案,利用了一些Angular的内部机制。我可以验证这适用于Angular 6,但当然要注意,你的情况可能不同。

还值得注意的是,TypeScript对此并不完全满意,所以在我的代码中,我不得不在这里和那里进行类型转换。为了代码清晰起见,我已经删除了这些转换。

const debugElement: DebugElement = window.ng.probe(document.querySelector('my-app'))
const app: MyAppComponent = debugElement.componentInstance;
app.increment();

0

你可以从Bootstrap回调函数中完成它:

bootstrap(AppComponent, [
  ROUTER_PROVIDERS,
]).then((app)=> {
  window.app = app
});

然后从控制台调用

app.instance.myMethod()

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接