Angular2 - 如何从应用程序的外部调用组件功能 [英] Angular2 - how to call component function from outside the app

查看:1731
本文介绍了Angular2 - 如何从应用程序的外部调用组件功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用具有回调的JavaScript对象。我想一旦回调被触发调用一个Angular2组件内部的功能。

I am using a javascript Object that has a callback. I want once the callback is fired to call a function inside an Angular2 component.

例如
HTML文件。

example HTML file.

    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 这是内部App.component.ts

How can i call the function runThisFunctionFromOutside which is inside App.component.ts

推荐答案

又见<一个href=\"http://stackoverflow.com/questions/35276291/how-do-expose-angular-2-methods-publicly/35276652?noredirect=1#comment58266532_35276652\">How不公开揭露角2种方法?

当组件constucted让自己分配到全局变量。然后,你可以从那里引用它,并调用方法。
不要忘了用 zone.run。(()=&GT; {...})所以角得到通知有关要求变化检测运行

When the component is constucted make it assign itself to a global variable. Then you can reference it from there and call methods. Don't forget to use zone.run(() => { ... }) so Angular gets notified about required change detection runs.

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

constructor(private _ngZone: NgZone){
  window.angularComponent = {component: this, zone: _ngZone};
}

ngOnDestroy() {
  window.angularComponent = null;
}

https://plnkr.co/edit/6gv2MbT4yzUhVUfv5u1b?p=$p$ PVIEW

在浏览器控制台,你必须从&LT开关; topframe&GT; plunker previewTarget .... 因为Plunker执行在的iFrame 的code。然后运行

In the browser console you have to switch from <topframe> to plunkerPreviewTarget.... because Plunker executes the code in an iFrame. Then run

window.angularComponentRef.zone.run(() => {window.angularComponentRef.component.callFromOutside('1');})

window.angularComponentRef.zone.run(() => {window.angularComponentRef.componentFn('2');})

这篇关于Angular2 - 如何从应用程序的外部调用组件功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆