javascript - 点击脚本上的 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 事件有效,但是,它会导致我的角度变化检测在我每次单击某个地方时触发,这会重新生成所有内容并丢弃脚本所做的更改。
我在这里做错了什么?
一般来说,我是角度和网络开发的新手,所以请大家不要对我太苛刻;)
解决方案
听起来您正在将某种项目添加到数组中,并且对于添加的每个项目,您都需要一个新按钮和一个单击处理程序。做这样的事情:
<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)
}
推荐阅读
- python - 从 FITS 图像返回 WCS 时遇到问题
- javascript - 想在对象数组中使用数组键作为新属性 javascript
- reactjs - 带有功能组件和钩子的 React 应用程序中的数据流
- dart - 无法在 Raspberry Pi 零 W 上加载 Dart SDK
- python - 将字符串类别转换为整数后如何找到结果?
- node.js - 有没有办法在“无头:假”模式下完全重新打开一个网站?
- laravel - Livewire,Laravel - 我可以从 Livewire 组件调用控制器“存储”方法吗?
- r - R readxl excel文件与美元符号
- android - 如何在 Android 中捕获签名时检查空位图
- c# - Visual Studio 无法识别新的表单名称/引用