0

I'm using JavaScript in Angular to automatically add new rows to a able when a function is called, this is done after the HTML has already loaded.

In each row of the table there is a cell containing a button.

I would like to use jQuery on the dynamically created buttons but since they are not part of the initial HTML the jQuery function is never called.

I tried using all of the Angular lifecycle hooks to see if any of them would work, but none do.

This is an example of the jQuery I would like to run when the button is clicked:

$( ".deleteButton" ).on("click",function() {
    alert("this is a button button");
    });

and this is the JavaScript of how my buttons are created

var deleteButton = document.createElement('button');
     deleteButton.innerHTML = 'Delete';
     deleteButton.type = "button"; 
     deleteButton.className = "deleteButton";

cell4.append(deleteButton);

table.append(row);

I would greatly appreciate any help regarding this!

trickster625
  • 37
  • 2
  • 9
  • 1
    ...and yet another dev mixing jQuery and Angular together. Please people, [STOP. DOING. THAT.](https://stackoverflow.com/questions/51304288/what-is-the-right-way-to-use-jquery-in-react#:~:text=No.,deleting%20stuff%20into%2Ffrom%20them.) – Jeremy Thille Apr 30 '21 at 08:43
  • 1
    @JeremyThille I'm just a student learning Angular trying to complete my homework assignment. No need to get pressed. – trickster625 Apr 30 '21 at 08:56
  • It's better not to mix different JS frameworks (e.g. jQuery and Angular) as @JeremyThille said. On jQuery point of view, I think what you are looking for is a delegated event handler. Bind the click event handler to the `table` or `tbody` and not to `.deleteButton`. Let the event bubble up. Something like `$("tbody").on("click", ".deleteButton", function() {...})` – jpllosa Apr 30 '21 at 09:03
  • 1
    @jpllosa No. Don't start introducing hacks and workarounds. If you do, your application will be an unmaintainable shaky mess. If you are learning Angular, then step 1 is to get rid of jQuery and use Angular. Also `document.createElement` and `.innerHTML` have nothing to do in an Angular app either. That's just not how it works. If you want an element to appear conditionally based on data, you use `*ngIf`. To attach a click hanler, you use `(click)="clickHandler()"`, period. That, or get rid of Angular and just use jQuery. – Jeremy Thille Apr 30 '21 at 10:13
  • When and where is the delete button creation occurs in the angular app? – elpddev May 01 '21 at 14:14

0 Answers0