uksz uksz - 9 months ago 81
jQuery Question

NgFor and JQuery not working as expected

I have an issue with making

work with
on click. The issue here is (as I think), that the jquery appends to DOM, before the ngFor has completed rendering. Here is the plnkr. As you can see, if you click on any of the
elements that are hard coded into html, the console log will trigger ('
clicked on li
'). However, if you click on the html created by
, it doesnt trigger console log anymore.

What can I do, to make it work for the html created by ngFor?


Answer Source

It's because you register the click handler before the data was actually received. They are loaded asynchronously using an HTTP request.

If you register your handlers after that and when the view is refresh, you will see the messages in the console:

constructor(private myService: MyService){
  console.log('myArr before', this.myArr);
    this.myArr = success;
    console.log('myArr received');

registerClickHandler() {
  $('li').on('click', function(e) {
    console.log('clicked on li');

That said, you should use the event support of Angular2:

  <li *ngFor="#obj of myArr" (click)="logClick(obj)">{{}}</li>

See this plunkr: