首页 > 解决方案 > 点击脚本上的 JQuery 触发更改检测 - Angular 6

问题描述

我的网站上有一个按钮,它将一个项目添加到一个数组中,然后尝试在将项目添加到数组后通过执行以下操作将使用 jQuery 的点击分配给新按钮。

$(function()
{
  $(document).on('click', '.btn-add', function(e)
  {
    e.preventDefault();
    //do something like change the color of an element
  });
});

使用 ngFor 我遍历这个数组并生成按钮。on click 事件有效,但是,它会导致我的角度变化检测在我每次单击某个地方时触发,这会重新生成所有内容并丢弃脚本所做的更改。

我在这里做错了什么?

一般来说,我是角度和网络开发的新手,所以请大家不要对我太苛刻;)

标签: javascriptjqueryangular

解决方案


听起来您正在将某种项目添加到数组中,并且对于添加的每个项目,您都需要一个新按钮和一个单击处理程序。做这样的事情:

<input #hello type="text"/> <!-- I'm guessing the values being added to the array are coming from an input but they could come from anywhere -->
<button (click)="addNewButton(hello.value)">

控制器代码:

this.values = []

addNewButton(value) {
  this.values = this.values.push(value)
  // this.values = [...this.values, value] // same thing without mutating the array
}

对于新按钮:

<ng-container *ngFor="let value of values; index as i">
  <button (click)="newButtonClicked(value, i)">{{ value }}</button>
</ng-container>

以及新按钮的控制器代码:

newButtonClicked(value, i) {
  console.log(value, i)
}

推荐阅读