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