Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Angular 2 component from another module / window

Tags:

angular

I am looking to access an Angular 2 component from another module as well as the window object. The window object would only be used for playing around in the browser console not actually for production (fyi). I was thinking I could 'export default class MyComponent' but that doesn't seem to work. How would I access the instantiated MyAppComponent class from another module / the window?

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

Then want to do something like this:

ang.increment();
like image 438
wayofthefuture Avatar asked Oct 31 '22 21:10

wayofthefuture


1 Answers

Here's another solution, which leverages some Angular internals. I can verify that this works in Angular 6, but of course, be aware that YMMV.

Also worth nothing, TypeScript isn't quite happy with this, so in my code, I had to cast things here and there. I've removed the casts here for code clarity.

const debugElement: DebugElement = window.ng.probe(document.querySelector('my-app'))
const app: MyAppComponent = debugElement.componentInstance;
app.increment();
like image 53
Jeff Fairley Avatar answered Nov 15 '22 08:11

Jeff Fairley