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.
- function callAngularFunction() {
- window.angularComponentReference.zone.run(() => { window.angularComponentReference.loadAngularFunction(); });
- }
Add Angular 2+ files into the demonstrateOutsideCall.html head tag.
- <html>
- <head>
- <app-root></app-root>
- <base href="/">
- <script src="D:/demonstrateOutside/runtime.js"></script>
- <script src="D:/demonstrateOutside/polyfills.js"></script>
- <script src="D:/demonstrateOutside/styles.js"></script>
- <script src="d:/demonstrateOutside/vendor.js"></script>
- <script src="d:/demonstrateOutside/main.js"></script>
- <script type="text/javascript">
- function callAngularFunction() {
- window.angularComponentReference.zone.run(() => { window.angularComponentReference.loadAngularFunction(); });
- }
- </script>
- </head>
- <body>
- <button type="button" onclick="callAngularFunction();">Call Angular 2 Function </button>
- </body>
- </html>
Create an Angular 2+ project using Angular CLI command and write the below code into AppComponent class.
- import { Component, NgZone } from '@angular/core';
-
- @Component({
- selector: 'app-root',
- templateUrl: './app.component.html',
- styleUrls: ['./app.component.css']
- })
- export class AppComponent {
- constructor(
- private ngZone: NgZone,
- ) { }
-
- ngOnInit() {
- window['angularComponentReference'] = { component: this, zone: this.ngZone, loadAngularFunction: () => this.angularFunctionCalled(), };
- }
- angularFunctionCalled() {
- alert('Angular 2+ function is called');
- }
- }
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".