我正在使用具有回调的JavaScript对象。我想要一旦回调被触发,调用一个Angular2组件内的函数。
例
HTML文件。
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
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"); }
参见
How do expose angular 2 methods publicly?
原文链接:https://www.f2er.com/angularjs/144445.html当组件被构建时,它将自己分配给一个全局变量。然后你可以从那里引用它,并调用方法。
不要忘记使用zone.run(()=> {…}),所以Angular会收到关于所需更改检测运行的通知。
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; }
在浏览器控制台中,您必须从< topframe>到plunkerPreviewTarget ….因为Plunker执行iFrame中的代码。然后跑
window['angularComponentRef'].zone.run(() => {window['angularComponentRef'].component.callFromOutside('1');})
要么
window.angularComponentRef.zone.run(() => {window.angularComponentRef.componentFn('2');})
一种替代方法
将派出角色外的事件,并按照Angular 2 – communication of typescript functions with external js libraries的解释倾听角色