例
HTML文件。@H_404_3@
@H_403_4@var run = new Hello('callbackfunction');
function callbackfunction(){
// how to call the function **runThisFunctionFromOutside**
}
<script>
System.config({
transpiler: 'typescript',typescriptOptions: { emitDecoratorMetadata: true },packages: {'js/app': {defaultExtension: 'ts'}}
});
System.import('js/app/main')
.then(null,console.error.bind(console));
</script>
我的App.component.ts@H_404_3@ @H_403_4@import {Component NgZone} from 'angular2/core'; import {GameButtonsComponent} from './buttons/game-buttons.component'; @Component({ selector: 'my-app',template: ' blblb' }) export class AppComponent { constructor(private _ngZone: NgZone){} ngOnInit(){ calledFromOutside() { this._ngZone.run(() => { this.runThisFunctionFromOutside(); }); } } runThisFunctionFromOutside(){ console.log("run"); }
当组件被构建时,它将自己分配给一个全局变量。然后你可以从那里引用它,并调用方法。
不要忘记使用zone.run(()=> {…}),所以Angular会收到关于所需更改检测运行的通知。@H_404_3@
@H_403_4@function callbackfunction(){
// window['angularComponentRef'] might not yet be set here though
window['angularComponent'].zone.run(() => {
runThisFunctionFromOutside();
});
}
constructor(private _ngZone: NgZone){
window['angularComponentRef'] = {component: this,zone: _ngZone};
}
ngOnDestroy() {
window.angularComponent = null;
}
Plunker example1@H_404_3@
在浏览器控制台中,您必须从< topframe>到plunkerPreviewTarget ….因为Plunker执行iFrame中的代码。然后跑@H_404_3@ @H_403_4@window['angularComponentRef'].zone.run(() => {window['angularComponentRef'].component.callFromOutside('1');})
要么@H_404_3@ @H_403_4@window.angularComponentRef.zone.run(() => {window.angularComponentRef.componentFn('2');})
将派出角色外的事件,并按照Angular 2 – communication of typescript functions with external js libraries的解释倾听角色@H_404_3@
Plunker example2(来自评论)@H_404_3@