Angular2 - how to call component function from outside the app

call typescript function from javascript angular
call angular 8 function from javascript
angular 8 call function from html
how to call function inside function in angular 4
how to call ngoninit of another component
call method from one component to another component angular 7
call function from another ts file
call javascript function from '@angular 4

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

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>

My 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 can i call the function runThisFunctionFromOutside which is inside App.component.ts

See also How do expose angular 2 methods publicly?

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['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

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

or

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

An alternative approach

would be to dispatch events outside Angular and listen to them in Angular like explained in Angular 2 - communication of typescript functions with external js libraries

Plunker example2 (from the comments)

How to expose angular 2 methods publicly?, When you call Angular methods from outside Angular, Angular doesn't part.call the exposed function inside angular //component window. How to invoke a function of an Angular Component from parant component. What I am trying to achieve here is to get a confirmation message before closing the modal in the parant component. The function inside the child component will check for unsaved changes. And if there are any unsaved changes, child will call then another modal for confirmation.

I basically followed this answer, but I didn't want my "outside" code to know anything about NgZone. This is app.component.ts:

import {Component, NgZone, OnInit, OnDestroy} from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: 'app.component.html'
})
export class AppComponent implements OnInit, OnDestroy {
  constructor(private ngZone: NgZone) {}

  ngOnInit() {
    window.my = window.my || {};
    window.my.namespace = window.my.namespace || {};
    window.my.namespace.publicFunc = this.publicFunc.bind(this);
  }

  ngOnDestroy() {
    window.my.namespace.publicFunc = null;
  }

  publicFunc() {
    this.ngZone.run(() => this.privateFunc());
  }

  privateFunc() {
    // do private stuff
  }
}

I also had to add a definition for TypeScript to extend the window object. I put this in typings.d.ts:

interface Window { my: any; }

Calling the function from the console is now as simple as:

my.namespace.publicFunc()

How to communicate with Angular components outside of Angular , It will then attach functions on the global window object that you can call outside of Angular. Basic usage: Inside of your Angular components,� method - Angular2-how to call component function from outside the app embed angular 2 app (4) I am using a javascript Object that has a callback.

Below is a solution.

function callbackfunction(){   
   window.angularComponent.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>

My 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){
  window.angularComponent = {runThisFunctionFromOutside: this.runThisFunctionFromOutside, zone: _ngZone};
}


    runThisFunctionFromOutside(){
      console.log("run");
    }
}

Simple Way To Execute A Function In A Component From Another , We can edit the “app.component.html” file with the below code. We can create a function inside the “first.component.ts” file and call from� I have two components as follows and I want to call a function from another component. Both components are included in the third parent component using directive. Component 1: @component( sel

An other approach without using global variables is to use pass a control object and bind its properties to the variables and methods to expose.

export class MyComponentToControlFromOutside implements OnChanges {

  @Input() // object to bind to internal methods
  control: {
    openDialog,
    closeDialog
  };

  ngOnChanges() {
    if (this.control) {
      // bind control methods to internal methods
      this.control.openDialog = this.internalOpenDialog.bind(this);
      this.control.closeDialog = this.internalCloseDialog;
    }
  }

  internalOpenDialog(): Observable<boolean> {
    // ...
  }

  internalCloseDialog(result: boolean) {
    // ...
  }
}
export class MyHostComponent {
   controlObject= {};
}
<my-component-to-control [control]="controlObject"></my-component-to-control>

<a (click)="controlObject.open()">Call open method</a>

Call Angular Function From JavaScript, In this blog, you will learn how to call any Angular 2+ function from app. component.css']; }); export class AppComponent {; constructor(� It will call a function inside service not a function in app component – Venkat Dec 1 '18 at 13:03 @Venkat that's true; On a hunch, I guessed that the OP's problem would be solved with a better architecture so I proposed a different approach altogether.

I had a similar situation when using the callback 'eventClick' of the fullCalendar library, whose callbacks are returning from outside the angular zone, causing my application to have partial and unreliable effects. I was able to combine the zone approach and a closure reference to the component as seen below in order to raise an output event. Once I started executing the event inside of the zone.run() method the event and it's effects were once again predictable and picked up by angular change detection. Hope this helps someone.

constructor(public zone: NgZone) { // code removed for clarity
}

ngOnInit() {
    this.configureCalendar();
}

private configureCalendar() {
    // FullCalendar settings
    this.uiConfig = {
        calendar: { // code removed for clarity

        }
    };

    this.uiConfig.calendar.eventClick = this.onEventClick();

}

private onEventClick() {
    const vm = this;

    return function (event, element, view) {
        vm.zone.run(() => {
            vm.onSequenceSelected.emit(event.sequenceSource);                    
        });

        return false;

    };
}

angular Angular2 how to call component function from outside the , import {Component, NgZone, OnInit, OnDestroy} from '@angular/core'; @ Component({ selector: 'my-app', templateUrl: 'app.component.html' }) export class � I have an angular 2 webpack project where I currently have some functions that are repeated throughout several components. I would like to inherit all of these components from a "master" class OR component (whichever works), in order to be able to call my functions from all my components that need them.

Using Angular 2 Components In a Non-Angular App, I am using a javascript Object that has a callback. Once the callback is fired I want to call a function inside an Angular2 component. example HTML file. var run� i want to call the filter directly from the component, not from the html template – Arron Apr 28 '16 at 11:53 Pipes are supposed to be used in HTML. If you want to call it directly then just create an instance let f = new filter() and then call it like let result = f.transform(value, [filterArg]); – Günter Zöchbauer Apr 28 '16 at 11:55

How do I call a function from an external js file? : Angular2, We wanted to write some new Angular 2 components and even Loading components from outside Angular dynamically The third line then calls the onInit function if it's passed in with an instance of the Component type. The first and second messages are from app.component.ts and the third one is from another component which is from my-component. So we are able to access the service among multiple components. The advantage of doing it this way is that, if we change anything in any of these components, it will also reflect the change in other components.

Run an angular 2 component method from JavaScript outside the , I need to call a file.init() function when the page renders. import { Component, OnInit } from '@angular/core' declare var myFunction,index,init:any and for a while in beta if the function was a promise you needed to run it outside the angular zone. Angular app to help you/your team translate your website into another� We are then using the decorator to define a component. The component has a selector called ‘my-app’. This is nothing but our custom html tag which can be used in our main html page. Now, let’s go to our index.html file in our code. Let’s make sure that the body tag now contains a reference to our custom tag in the component.

Comments
  • Could you give us more context? Where do you run object take place? How your callback is called? Thanks!
  • run is called in the html, outside <my-app></my-app>.
  • Okay. And the callback?
  • looks like you just need to use a closure to access the component within a callback, `ngOnInit(){ let vm = this; calledFromOutside() { vm._ngZone.run(() => { vm.runThisFunctionFromOutside(); }); } }
  • If minification changes the names it might be better to assign a function reference instead of a class reference (window.angularComponentRef = {zone: zone, /*component: this*/ componentFn: this.callFromOutside};).
  • check the outside button in index.html plnkr.co/edit/e77JkHmO7n5FYoKSXnIL?p=preview
  • @GünterZöchbauer thanks for the response. The issue I had, was calling a function inside a child. I had to make in each constructor the NgZone event.
  • Once upgraded to RC4, window.angularComponentRef is throwing error, Property 'angularComponentRef' does not exist on type 'Window'.while starting the npm. Is there any alternative method to replace window.angularComponentRef
  • @GünterZöchbauer I followed this steps but getting this problems: stackoverflow.com/questions/39849369/linkedin-with-angular-2
  • this works for me but publicFunc is always called twice?
  • this is more cleaner code, it worked for me, thanks!
  • This is an excellent solution and works. I think should be voted as the accepted answer.
  • How can I access variable which is defined in AppComponent, through runThisFunctionFromOutside function?