#18: πŸ—‘ Remove item

The user should be able to remove any item, whether it's still active or completed. Removing an item will be done by clicking a button, aptly named "remove". In this chapter, we'll learn how to add this functionality to our project.

Add the "remove" button

Add a "remove" button to the item template, with a click event handler that calls a removeItem method (which we'll create in a moment):

src/app/item/item.component.ts
template: `
  <div class="todo-item">
    {{ todoItem.title }}

    <button class="btn btn-red" (click)="removeItem()">
      remove
    </button>
  </div>
`,

Add a new output to the ItemComponent class, which will be emitted to the list manager when a user presses its remove button:

src/app/item/item.component.ts
@Output() remove:EventEmitter<any> = new EventEmitter();

Make sure to import both EventEmitter and Output:

src/app/item/item.component.ts
import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core';

Add a method to the ItemComponent class to actually emit the event. This method will be called when the user clicks the "remove" button:

src/app/item/item.component.ts
removeItem() {
  this.remove.emit(this.todoItem);
}

Remove the todo item

We need to respond to the remove event. Let's add it to the template, inside the <todo-item> tag:

src/app/list-manager/list-manager.component.ts
<todo-item [todoItem]="item" (remove)="removeItem($event)"></todo-item>

Now we just need to add the method removeItem() to the ListManagerComponent class:

src/app/list-manager/list-manager.component.ts
removeItem(item) {
  this.todoList = this.todoListService.removeItem(item);
}

Remove the todo item from local storage

src/app/todo-list.service.ts
removeItem(item) {
  return this.storage.destroy(item);
}

Last updated