0

I am building a todo list in Angular 5 and I'm trying to delete several tasks. Each task is a checkbox, if several tasks are checked all of theses tasks should be deleted at the same time when I click the button DELETE ALL (function deleteSelected). But sometimes it works, sometimes not I don't understand why.

Here's my code so far:

**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++;
       }
     }

Thanks for your help

  • Try using the `filter` function instead to remove the ones you want to remove, e.g. `this.todos = this.todos.filter((todo) => todo.status != true)`, which will only keep todos where the status is not true – user184994 Apr 22 '18 at 10:14

2 Answers2

1

Inside your deleteSelected function, instead of doing

object.splice(index, 1);

Use

this.todos.splice(index, 1)

Reference: Remove Object from Array using JavaScript

Paritosh
  • 11,144
  • 5
  • 56
  • 74
0

For simplicity in your case could be used filter function:

this.todos = this.todos.filter((todo)=> !todo.status);
mykhailo.romaniuk
  • 1,058
  • 11
  • 20