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();
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With