1

I have an issue with making ngFor work with jQuery 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 li elements that are hard coded into html, the console log will trigger ('clicked on li'). However, if you click on the html created by ngFor, it doesnt trigger console log anymore.

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

Thanks

uksz
  • 18,239
  • 30
  • 94
  • 161
  • I guess it is connected to http://stackoverflow.com/questions/36011948/how-can-i-execute-code-only-after-my-view-with-its-ngfors-and-the-like-has-cha – uksz May 06 '16 at 13:09

1 Answers1

2

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);
  myService.getAsync().subscribe(success=>{
    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:

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

See this plunkr: http://plnkr.co/edit/aAmUQL?p=preview.

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360