1

This question is similar to that one Call Angular Function with Jquery

But I think mine example have small diferences.

On Angular project I have a button:

<button id="button1" #tbName title="tbName" class="btn btn-lg btn-outline-primary" (click)="open(content,tbName.title)">Launch demo modal</button>

On TS file there is a method:

open(content, title) {
    console.log(document.getElementById('button1').getAttribute('title'));
    this.id_desk = document.getElementById('button1').getAttribute('title');
    this.modalService.open(content, { centered: true, container: '#test', ariaLabelledBy: 'modal-basic-title' }).result.then((result) => {

        this.closeResult = `Closed with: ${result}`;
    }, (reason) => {

        this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
    });
}

How should looks like jQuery function that will directly call open(content,title) angular method?

Krishna Rathore
  • 8,604
  • 3
  • 23
  • 46
Sepcio
  • 165
  • 4
  • 14

2 Answers2

5

I Strongly advise you to learn to use Angular (& w/o JQuery) instead of mixing the twos.

Now we're on SOF and you asked something. There's a lot wrong with your code, but hey, that's not my project, so I'll just answer.

if you want to access an Angular function with JQuery, bind it to the window like so.

ngOnInit() {
  window['MyComponent']['open'] = this.open.bind(this);
}

Now in JQuery you can access it with

$(...).click(function() {
  window.MyComponent.open('content of the modal', 'title of the modal');
});
1

In general, you cannot trigger a method defined within and Angular component, because for that you need the instance of the class. Notice how you never call new Component() anywhere in your code? Instead you just specify classes and tie them up with templates and let Angular do the rest.

That said, you can pass the method as a reference to a something global. For example, you can do something like this:

class Component {
  public fn () {} // <-- say you need this function
  constructor () {
    window.fn = this.fn.bind(this)
  }
}

After the constructor is executed, you'll be able to call window.fn() from any file. Note that this approach fails if you expect to have multiple instance of the component. If you do, you need to save the method references in an array or an object.

That said, this is strongly discouraged as it makes code a mess to read.

Lazar Ljubenović
  • 17,499
  • 8
  • 54
  • 86