uksz
uksz

Reputation: 18699

NgFor and JQuery not working as expected

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

Upvotes: 1

Views: 1495

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202138

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.

Upvotes: 2

Related Questions