Chetan Purohit
Chetan Purohit

Reputation: 392

How to call function written in Angular Component from external javascript file?

I have written an external JavaScript file for creating dynamic UI on a page. I need to call a function written in component class on click of dynamically created button. Technically I am trying to call a function from plain JavaScript file. Any help will be appreciated.

Below is an example:

Suppose my Home.Component.ts file has a function 'showToast()'

export class HomeComponent {

    public showToast() {

        this.messageService.showToast();
    }
} //end of 'HomeComponent'

and my custom.js file is having a code for finding click event as below:

btn.onClick() {

     //I want to call showToast() function from here.
}

Upvotes: 0

Views: 404

Answers (1)

Stephen
Stephen

Reputation: 11

  • Create a CND package
  • Insert a package as a script file in index.html
  • Use the service file

Example code:

import { Injectable } from '@angular/core';
declare var CryptoJS: any;
export class CryptService {

  constructor() { }

  public decrypt(encryptedString, random) {
    return new Promise((result, reject) => {
      const bytes = CryptoJS.AES.decrypt(encryptedString, random);
      result(bytes.toString(CryptoJS.enc.Utf8));
    });
  }

  public encrypt (payload, user_id) {
    return CryptoJS.AES.encrypt(payload, user_id).toString();
  }

}

module.ts

this.load('https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js');

  load(scriptUrl: string) {
    if (isPlatformBrowser(this.platformId)) {
      let node: any = document.createElement('script');
      node.src = scriptUrl;
      node.type = 'text/javascript';
      node.async = true;
      node.charset = 'utf-8';
      document.getElementsByTagName('head')[0].appendChild(node);
    }
  }

Upvotes: 1

Related Questions