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

前端之家收集整理的这篇文章主要介绍了从另一个模块/窗口访问Angular 2组件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我期待从另一个模块以及窗口对象访问Angular 2组件.窗口对象仅用于在浏览器控制台中播放而不是实际用于生产(fyi).我以为我可以’导出默认类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();

解决方法

这是另一个利用一些Angular内部结构的解决方案.我可以验证这在Angular 6中有效,但当然要注意YMMV.

也没什么值得的,TypeScript对此并不满意,所以在我的代码中,我不得不在这里和那里施展东西.为了清晰起见,我在这里删除了演员阵容.

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

猜你在找的Angularjs相关文章