Angular2 – 如何从应用程序外部调用组件函数
发布时间:2020-12-17 08:11:58 所属栏目:安全 来源:网络整理
导读:我正在使用具有回调的JavaScript对象。我想要一旦回调被触发,调用一个Angular2组件内的函数。 例 HTML文件。 var run = new Hello('callbackfunction'); function callbackfunction(){ // how to call the function **runThisFunctionFromOutside** } scrip
我正在使用具有回调的JavaScript对象。我想要一旦回调被触发,调用一个Angular2组件内的函数。
例 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"); } 我如何调用AppAttribute中的runThisFunctionFromOutside函数
参见
How do expose angular 2 methods publicly?
当组件被构建时,它将自己分配给一个全局变量。然后你可以从那里引用它,并调用方法。 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 在浏览器控制台中,您必须从< 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的解释倾听角色 Plunker example2(来自评论) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |