簡體   English   中英

從另一個模塊/窗口訪問Angular 2組件

[英]Access Angular 2 component from another module / window

我期待從另一個模塊以及窗口對象訪問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();

你可以通過bootstrap回調來做到這一點:

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

然后從控制台調用

app.instance.myMethod()

使您的組件成為全局變量

constructor() {
    window['AppComponent'] = {Appcomponent: {all:this}};
 }

示例: https//stackblitz.com/edit/angular-xjaaen

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM