[英]I would like to add a remove button in my Angular App
我有一个 Angular 应用程序,我想为一个 div 元素添加一个删除按钮,我目前有一个添加按钮,如下所示:
.ts 文件。
uploads = [];
addUp() {
this.uploads.push(this.uploads.length);
}
我试过了
removeUp() {
this.uploads.remove(this.uploads.length);
}
此代码链接到此按钮,如下所示:
<button class="btn" (click)="addUp()">Add</button>
HTML
<div class="col" *ngFor="let upload of uploads">
<h2>Upload</h2>
</div>
我将如何做删除版本?
不能使用remove
函数从数组中删除项目。
要从数组中删除元素,您应该使用splice :
removeUpload(uploadItem) {
// get index/position of uploadItem within array
const index: number = this.uploads.indexOf(uploadItem);
// if index returned is negative it means element not found in array
// else: (positive) index can be used
// e.g. to remove the single element at this position
if (index !== -1) {
this.uploads.splice( index, 1 );
}
}
这从索引位置中删除了一个元素(因此这里的第二个参数是1
)。
当然,您必须将参数upload
作为参数添加到按钮的点击事件,以便函数知道它必须删除数组的哪个元素:
<button class="btn" (click)="removeUpload( upload )" title="remove this">x</button>
请参阅stackblitz 上的演示。
如果要删除数组的第一个元素,请使用 array。 移位() 。 如果要删除数组的最后一个元素,请使用 array. 流行音乐() 。 这两个函数都返回被移除的元素。
我不确定您为什么将数组的长度添加/删除( push
相应的splice
)到uploads
数组。 数组是存储自身的当前大小还是上传项目对象?
如果我理解正确,您正在尝试实现相同的按钮实现,但对于 remove 方法。
使用: <button class="btn" (click)="removeUp()">Remove</button>
并更改 removeUp 方法以使用splice
而不是remove
:
removeUp() {
this.uploads.splice(this.uploads.length, 1)
}
看看这里回答了一个类似的问题类似的问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.