Menu Close

How to call component function from outside the app with Angular?

Sometimes, we want to call component function from outside the app with Angular.

In this article, we’ll look at how to call component function from outside the app with Angular.

How to call component function from outside the app with Angular?

To call component function from outside the app with Angular, we need to use NgZone.

For instance, we write

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() {
    // ...
  }
}

to inject NgZone into our AppComponent.

Then we define the publicFunc method that calls this.ngZone.run with a callback that calls this.privateFunc.

Next, in ngOnInit, we set window.my.namespace.publicFunc to this.publicFunc.bind(this) so that publicFunc is exposed to the outside with the component as the value of this inside publicFunc.

Then we can call publicFunc outside our app with

my.namespace.publicFunc()

Conclusion

To call component function from outside the app with Angular, we need to use NgZone.

Posted in Angular, Angular Answers