我使用的是一个有回调的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");
}

如何调用应用程序内部的函数runThisFunctionFromOutside.组成部分ts

推荐答案

另见How do expose angular 2 methods publicly?

构造组件时,请将其自身分配给全局变量.然后可以从那里引用它并调用方法.

 function callbackfunction(){   
   // window['angularComponentRef'] might not yet be set here though
   window['angularComponent'].zone.run(() => {
     runThisFunctionFromOutside(); 
   });
 }

construct或(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');})

An alternative approach

将是在Angular 之外分派事件并以Angular 监听它们,如在Angular 2 - communication of typescript functions with external js libraries中所解释的那样

Plunker example2 (from the comments)

Angular相关问答推荐

如何用ANGLE指令覆盖Html元素的数据绑定属性

有没有其他代码可以用函数的方式写成Angular ?

如何将表单作为Angular 分量输入传递?

我的验证器收到一个始终为空的可观察值

无法绑定到formControl,因为它不是input的已知属性

由于ngcc操作失败,Angular扩展可能无法正常工作

Angular 迁移 14 到 15 / 16:angular universal 是否停止将 <!-- this page was prerendered with angular universal --> 用于预渲染页面?

PrimeNG 避免在同一位置使用不同键的 cogo toast 重叠

将 autoSpy 与 ng-mocks 一起使用时,如何重置 jasmine 间谍调用?

Storybook 和 Angular 交互游戏测试未定义预期

当访问令牌在 MSAL for Angular 中过期时如何重定向用户?

我想将一个对象传递给一个子组件.我做了一切,但没有任何效果. (Angular )

Angular SPA 和 .Net 6 API 之间未连接 Application Insights Map

单选按钮的Angular2 Reactive Forms formControl

如何在 Angular 2 中获取与 ElementRef 关联的组件的引用

如何将新的 FormGroup 或 FormControl 添加到表单

无法获得 angular-material md-sidenav 的 100% 高度

Angular 应用程序中的语法错误:Unexpected token <

Angular:找不到不同的支持对象[object Object]

如何处理Angular2中的查询参数