Tuesday, February 27, 2018

Angualr 5 Trick: include external JS

Angualr 5 Trick: include external JS
This blog first shows how to create an Angular 5 application skeleton, then shows how to call Angular component’s methods from an external JS.

Install angular-cli

npm install -g @angular/cli
(note @, this will install angular versions >4; if omitted, will install angular versions >2)

Create an angular application

ng new AngularTrick

Run application in Webstorm

Click on package.json, and click “show ng scripts”, run “start”.
(I do not use Webstorm to debug javascript, Chrome’s developer tool works out very well)

Create dropdown menu on top

The menu is created with Bootstrap:

To do this, need to import:
"@ng-bootstrap/ng-bootstrap": "1.0.0",
"bootstrap": "4.0.0-alpha.6",

To incorporate bootstrap css styles into the application, in .angular-cli.json, add bootstrap css:
"styles": [


Create the menu in navbar.component.html:
<nav class="navbar navbar-inverse navbar-toggleable-md jh-navbar">
  <div class="jh-logo-container float-left">
    <a class="jh-navbar-toggler hidden-lg-up float-right" href="javascript:void(0);" data-toggle="collapse"
       data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false"
       aria-label="Toggle navigation" (click)="toggleNavbar()">
      <i class="fa fa-bars"></i>

    <a class="navbar-brand logo float-left" routerLink="/" (click)="collapseNavbar()">
      <span class="logo-img"></span>
      <span class="navbar-title">AngularTrick</span>

  <div class="navbar-collapse collapse" id="navbarResponsive" [ngbCollapse]="isNavbarCollapsed">
    <ul class="navbar-nav ml-auto">
      <li class="nav-item" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">
        <a class="nav-link" routerLink="/" (click)="collapseNavbar()">
          <i class="fa fa-home" aria-hidden="true"></i>

      <li ngbDropdown class="nav-item dropdown pointer" routerLinkActive="active"
          [routerLinkActiveOptions]="{exact: true}">
        <a class="nav-link dropdown-toggle" ngbDropdownToggle href="javascript:void(0);" id="workfloweditor-menu">
                        <i class="fa fa-th-list" aria-hidden="true"></i>
                        <b class="caret"></b>

        <ul class="dropdown-menu" ngbDropdownMenu>
            <a class="dropdown-item" [routerLink]="['/trick-external-js-call-angular']" routerLinkActive="active"
               [routerLinkActiveOptions]="{ exact: true }" (click)="collapseNavbar()">
              <i class="fa fa-fw fa-asterisk" aria-hidden="true"></i>
              <span>External JS Call Angular Component Methods</span> 

And the corresponding navbar.component.ts:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

    selector: 'app-navbar',
    templateUrl: './navbar.component.html',
    styleUrls: [


export class NavbarComponent implements OnInit {
    isNavbarCollapsed: boolean;
    constructor(private router: Router) {

    ngOnInit() {

    collapseNavbar() {
        this.isNavbarCollapsed = true;

    toggleNavbar() {
        this.isNavbarCollapsed = !this.isNavbarCollapsed;


In app.component.html, add router-outlet:

  <router-outlet name="navbar"></router-outlet>

<div class="container-fluid" style="height: 100%; min-height:100%;">
  <div class="card"  style="height: 100%; min-height:100%;">
    <router-outlet name="popup"></router-outlet>

Add app.route.ts to configure navbar route:

import { Route } from '@angular/router';
import {NavbarComponent} from './navbar.component';

const navbarRoute: Route = {
  path: '',
  component: NavbarComponent,
  outlet: 'navbar'

export const LAYOUT_ROUTES = [

Import navbar route in app.module.ts:
imports: [
  RouterModule.forRoot(LAYOUT_ROUTES, { useHash: true }),

Include an external javascript into the application

There are two options.

One is to include the file in .angular-cli.json:
"scripts": [
Another approach is to use webpack plugin CopyWebpackPlugin , and copy these files into the target directory, with this approach, you can include the external files in index.html:

new CopyWebpackPlugin([

Call Angular Component’s methods from an external JS

Create a module for this trick:

trick1-main.html shows the following:

<div class="row">
  <h3 class="col-lg-12">Trick to include external javascripts and having external javascripts invoking angular component methods</h3>

<div class="row">
  <div class="col-lg-12">
  <span>this button will invoke a function from outside.js, which in turn will call an Angular component's method</span>

  <div class="col-lg-2">
     <input type="button" value="ExternalJSCallAngualr" onclick="outsideSetHello()"/>

  <div class="col-lg-12" *ngIf="showHelloFlag">Hello World</div>

  <div class="col-lg-12" style="margin-top:15px">
    <span>this button will invoke an Angular component's method, which in turn will call an outside javascript</span>

  <div class="col-lg-2">
    <input type="button" value="AngularCallOutsideJS" (click)="angularCallOutside()"/>


The corresponding trick1-main.ts:

import {Component, OnDestroy, OnInit,NgZone} from '@angular/core';
declare var outsideSetHello2: any;

    selector: 'external-js-call-angular-main',
    templateUrl: './trick1-main.html',

export class ExternalJSCallAngularMainComponent  implements OnInit,OnDestroy {


    private _ngZone: NgZone){


  ngOnInit() {    

    window['ExternalJSCallAngularMainComponent'] = this;

  ngOnDestroy() {



To call a method from an external javascript, declare the method as any:
declare var outsideSetHello2: any;

To allow an external javascript call an angular component’s methods, put the component into window global variable:
window['ExternalJSCallAngularMainComponent'] = this;

outside.js contains 2 simple methods:
function outsideSetHello(){

function outsideSetHello2(){
  alert("hello world2")


  1. I simply wanted to write down a quick word to say thanks to you for those wonderful tips and hints you are showing on this site. Best AWS Training in Bangalore