Call Angular Function From JavaScript

In this blog, you will learn how to call any Angular 2+ function from JavaScript.

This small trick will help you to call any Angular 2+ function from a JavaScript function.
 
Prerequisite
 
Having prior knowledge of Angular 2+ and JavaScript will be helpful.
 
Please visit the official website to create an Angular 2+ project using Angular CLI. https://angular.io/start
 
Add this function into theHTML page head tag.
  1. function callAngularFunction() {  
  2.    window.angularComponentReference.zone.run(() => { window.angularComponentReference.loadAngularFunction(); });  
  3. }  
Add Angular 2+ files into the demonstrateOutsideCall.html head tag.
  1. <html>  
  2. <head>  
  3.     <app-root></app-root>  
  4.     <base href="/">  
  5.     <script src="D:/demonstrateOutside/runtime.js"></script>  
  6.     <script src="D:/demonstrateOutside/polyfills.js"></script>  
  7.     <script src="D:/demonstrateOutside/styles.js"></script>  
  8.     <script src="d:/demonstrateOutside/vendor.js"></script>  
  9.     <script src="d:/demonstrateOutside/main.js"></script>  
  10.     <script type="text/javascript">  
  11.         function callAngularFunction() {  
  12.             window.angularComponentReference.zone.run(() => { window.angularComponentReference.loadAngularFunction(); });  
  13.         }  
  14.     </script>   
  15. </head>  
  16. <body>  
  17.     <button type="button" onclick="callAngularFunction();">Call Angular 2 Function </button>  
  18. </body>  
  19. </html>  
Create an Angular 2+ project using Angular CLI command and write the below code into AppComponent class.
  1. import { Component, NgZone } from '@angular/core';  
  2.   
  3. @Component({  
  4.   selector: 'app-root',  
  5.   templateUrl: './app.component.html',  
  6.   styleUrls: ['./app.component.css']  
  7. })  
  8. export class AppComponent {  
  9.   constructor(  
  10.     private ngZone: NgZone,  
  11.   ) { }  
  12.   // tslint:disable-next-line:use-life-cycle-interface  
  13.   ngOnInit() {  
  14.     window['angularComponentReference'] = { component: this, zone: this.ngZone, loadAngularFunction: () => this.angularFunctionCalled(), };  
  15.   }  
  16.   angularFunctionCalled() {  
  17.     alert('Angular 2+ function is called');  
  18.   }  
  19. }  
Note that the window object window['angularComponentReference'] in AppCommonent Class and window.angularComponentReference in JavaScript should match.
 
Now, build the project by running the command ng build and save all files into the demonstrateOutside folder and reference these file into demonstrateOutsideCall.html page.
 
Now, simply open the HTML page into any browser and click on the button "Call Angular 2 Function" which results in an alert message "Angular 2+ function is called".