Angular2 – 如何从应用程序外部调用组件函数

前端之家收集整理的这篇文章主要介绍了Angular2 – 如何从应用程序外部调用组件函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用具有回调的JavaScript对象。我想要一旦回调被触发,调用一个Angular2组件内的函数


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

我如何调用AppAttribute中的runThisFunctionFromOutside函数@H_404_3@

参见 How do expose angular 2 methods publicly?

当组件被构建时,它将自己分配给一个全局变量。然后你可以从那里引用它,并调用方法
不要忘记使用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');})

一种替代方法@H_404_3@

将派出角色外的事件,并按照Angular 2 – communication of typescript functions with external js libraries的解释倾听角色@H_404_3@

Plunker example2(来自评论)@H_404_3@

猜你在找的Angularjs相关文章