0

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.
}
2

1 Answer 1

1
  • 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);
    }
  }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.