简体   繁体   English

NgFor和JQuery无法正常工作

[英]NgFor and JQuery not working as expected

I have an issue with making ngFor work with jQuery on click. 我在使ngForjQuery一起使用时遇到问题。 The issue here is (as I think), that the jquery appends to DOM, before the ngFor has completed rendering. 我认为,这里的问题是,在ngFor完成渲染之前,jquery会附加到DOM。 Here is the plnkr . 这是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 '). 如您所见,如果单击任何硬编码到html中的li元素,则控制台日志将触发(“ clicked on li ”)。 However, if you click on the html created by ngFor , it doesnt trigger console log anymore. 但是,如果单击ngFor创建的html,它将不再触发控制台日志。

What can I do, to make it work for the html created by ngFor? 我该怎么办,以使其适用于ngFor创建的html?

Thanks 谢谢

It's because you register the click handler before the data was actually received. 这是因为您在实际接收数据之前注册了点击处理程序。 They are loaded asynchronously using an HTTP request. 它们使用HTTP请求异步加载。

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: 也就是说,您应该使用Angular2的事件支持:

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

See this plunkr: http://plnkr.co/edit/aAmUQL?p=preview . 请参阅以下代码: http ://plnkr.co/edit/aAmUQL?p=preview。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM