本文介绍了角度-单击该项目即可从数组中删除该项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Angular(具体来说是v6),并试图构建一个简单的待办事项清单.

I'm learning Angular (v6 to be specific), and trying to build a simple to do list.

我能够将项目添加到数组并显示在列表中,但无法弄清楚如何在单击该项目时删除特定项目.

I'm able to add items to an array and display in a list but cannot figure out how to delete specific items on click of that item.

当前代码会在单击时删除整个数组.这是我的代码:

Current code deletes the entire array on click. Here's my code:

app.component.html

app.component.html

 <h1>To Do List</h1>
  <label for="">What do you need to to?</label>
  <input type="text" [(ngModel)]="listItem">
  <br>
  <button (click)="addToList()">Add</button>
  <hr>
  <ul>
    <li *ngFor="let toDo of toDoList" (click)="removeFromList($event)">{{ toDo }}</li>
  </ul>

app.component.ts

app.component.ts

export class AppComponent {
  title = 'to-do-list-app';
  listItem = '';
  toDoList = [];

  addToList() {
    this.toDoList.push(this.listItem);
  }

  removeFromList(addedItem) {
    this.toDoList.splice(addedItem);
  }

推荐答案

将项目索引传递给splice并指定要删除的一项:

Pass the item index to splice and specify that one item is to be removed:

<li *ngFor="let toDo of toDoList; let i = index" (click)="toDoList.splice(i, 1)">

有关演示,请参见此stackblitz .

这篇关于角度-单击该项目即可从数组中删除该项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 23:25