-1

I am working on a task where I have an event listener window.addEventListener which is in javascript, based on event data I want to trigger a function of typescript and pass the data to that function. the point I am not getting is how to call typescript function in javascript. I have tried different things like a global variable, returning a value from js function but didn't work for me.

ngOnInit() {
  (function ($) {
    $(document).ready(function () {
      window.addEventListener('message', function (event) {
        console.log("Rece new Call event ibrahim " + JSON.stringify(event.data));
        let obj: any = JSON.stringify(event.data)
        obj = JSON.parse(obj);
        console.log(obj)
        if (obj.EventType === "handleContactIncoming") {
        
          var num = obj.Number
         // here i want to trigger Typescript function and pass this num to that function.
            
        }
        else if (event.data === "endCall") {
     //     return "No"
          // var dbBtn = document.getElementById("db");
          // dbBtn.click();
        }
        // $('.sidebar-menu').tree();
      });
     
    });
  });
  • 1
    Does this answer your question? [Calling properly TypeScript code from JavaScript](https://stackoverflow.com/questions/26427722/calling-properly-typescript-code-from-javascript) – mutantkeyboard Jul 21 '20 at 11:55
  • Does this answer your question? [Accessing class method from console in angular typescript](https://stackoverflow.com/questions/63008382/accessing-class-method-from-console-in-angular-typescript) – Philipp Meissner Jul 21 '20 at 11:58

2 Answers2

2

There is no difference when calling function from TS or JS. Finally there's always only JS in the browser, TS exists only in source code.

Also your code is a bit messy. There's no need to use jQuery inside angular (with an exception when you want to use some plugins or custom controls).

$(document).ready(function () {

is also redundant, if angular works the document is for sure ready.

Azargoth
  • 375
  • 2
  • 7
1

Your code is quite messy and breaks separation of concerns. You should not use jQuery inside Angular. The injectable EventManager provides functionality for setting events on the window or document objects.

constructor(private readonly eventManager: EventManager) {}

ngOnInit(): void {
  this.eventManager.addGlobalEventListener(target, event, () => {
    this.hello();
  });
}

hello(): void {
  console.log('Hello World!');
}
Mark
  • 521
  • 6
  • 15