如何使用Angular 5删除待办事项列表中的多个任务

时间:2018-04-22 10:05:05

标签: angular

我正在Angular 5中构建一个待办事项列表,我试图删除多个任务。每个任务都是一个复选框,如果检查了几个任务,当我单击按钮DELETE ALL(函数deleteSelected)时,应同时删除所有这些任务。但有时它有效,有时候我不明白为什么。

到目前为止,这是我的代码:

**todo.component.html**

<div class="main">
 <h1>To-do-list Alexandre, Cissé</h1>
 <div class="addItem">
  <form (ngSubmit)="addTodo()" #todoForm="ngForm">
   <input [(ngModel)] = "newTodo.newTodo" placeholder="Add a new todo" class="addText" name="newTodo">
   <button type="submit" class="btn-success">ADD</button>
  </form>
 </div>

<ul>
 <li *ngFor="let todo of todos; let number = index">
   <input type="checkbox" [(ngModel)]="todo.status">
   {{todo.newTodo}}
   <button (click)="deleteTodo(number)" class="btn-warning">Delete</button>
 </li>
</ul>
<br />
 <button (click)="deleteSelected()" class="btn-danger">DELETE ALL</button>
</div>

**todo.component.ts**

import { Component, OnInit } from '@angular/core';
import { Todo } from './todo';

@Component({
selector: 'app-todo',
templateUrl: './todo.component.html',
styleUrls: ['./todo.component.css']
})

export class TodoComponent implements OnInit {
  todos: Todo[] = [];
  newTodo = new Todo();

  addTodo () {
    this.todos.push(this.newTodo);
    this.newTodo = new Todo();
     }

  deleteTodo (index) {
    this.todos.splice(index, 1);
   }


  deleteSelected () {
    this.todos.forEach(function(value, index, object) {
    if (value.status === true) {

     //here I can't understand why it doesn't work

     object.splice(index, 1);
     }

     });
    }


   constructor() { }

    ngOnInit() {
   }

   }


   **todo.ts**

   export class Todo {
     static lastId = 0;
     public id: number;
     public newTodo: string;
     public status: boolean;

   constructor() {
     this.id = Todo.lastId + 1;
     this.status = false;
     Todo.lastId++;
       }
     }

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

deleteSelected功能中,而不是

object.splice(index, 1);

使用

this.todos.splice(index, 1)

参考: Remove Object from Array using JavaScript

答案 1 :(得分:0)

为简单起见,可以使用filter函数:

this.todos = this.todos.filter((todo)=> !todo.status);