【问题标题】:I would like to add a remove button in my Angular App我想在我的 Angular 应用程序中添加一个删除按钮
【发布时间】:2019-07-07 16:25:15
【问题描述】:

我有一个Angular App,我想为一个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>

我将如何执行删除版本?

【问题讨论】:

标签: javascript html angular typescript


【解决方案1】:

如果我理解正确,您正在尝试实现相同的按钮实现,但使用 remove 方法。

使用:&lt;button class="btn" (click)="removeUp()"&gt;Remove&lt;/button&gt;

并且还将removeUp方法更改为使用splice而不是remove

removeUp() {

   this.uploads.splice(this.uploads.length, 1)

}

看看这里回答的类似问题Similar question

【讨论】:

  • 感谢 Alexandros,但 TS 文件中的代码不能用于删除元素
  • 好的,所以你的问题是 removeUp 方法。你想删除什么?列表的最后一个元素上传?
  • 检查新编辑的答案。您使用ngFor 编辑的额外html 是正确的,但我看到您没有使用列表中的upload 对象。您只是将元素显示为 h2 的文本。你不应该使用它吗?
  • 亲爱的@rob,请告诉我们什么和什么东西不起作用(即包括:控制台输出、错误消息、堆栈跟踪等)。然后我们可以更快地分析并直接解决它。
  • 好的hc_dev下次会做
【解决方案2】:

您不能使用函数 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>

demo on stackblitz

快捷方式

如果要删除数组的 first 元素,请使用 array.shift()。 如果要删除数组的 last 元素,请使用 array.pop()。 两个函数都返回删除的元素。

从数组中添加/删除什么?

我不确定您为什么将数组的长度添加/删除(push 相应的splice)到uploads 数组。数组是存储自身的当前大小还是upload-item-objects?

另见

A: remove item from stored array in angular 2

【讨论】:

  • 上传将是您将文件上传到的输入,它现在只是一个

    标签,但概念与添加和删除元素相同。

  • 删除按钮不起作用 - 控制台中没有错误
  • @rob 抱歉,修复了我的代码 splice(uploadItem,1) 必须是 splice(index, 1),正如您已经认识到的那样。并添加了按钮-HTML。找到完整的演示链接。
猜你喜欢
  • 2021-03-26
  • 1970-01-01
  • 2020-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-27
  • 1970-01-01
相关资源
最近更新 更多