Home > Enterprise >  How can I remove items from a list of tasks in Angular?
How can I remove items from a list of tasks in Angular?

Time:11-17

I'm creating a scheduler in which I can add tasks I've done in a certain amount of time. The tasks get added in a to-do list-like manner.

I'm trying to remove individual items from a list both from the front-end and from LocalStorage but I haven't found a solution that works yet. The function I'm trying to make work is "RemoveTask()". Here's my code:

HTML:

<div class="modalbox" [class.active]="modalboxActive">
  <div class="modal">
    <p>What did you do?</p>

    <input type="text" [(ngModel)]="activity.name" maxlength="22" />
    <button (click)="addTask()" [disabled]="activity.name === ''">OK</button>
  </div>
</div>
<div class="boxSuper">
  <div class="boxLeft">
    <div class="containerUp">
      <button id="start" (click)="startTimer()">START</button>
      <button id="pause" (click)="pauseTimer()">PAUSE</button>
      <button id="stop" (click)="stopTimer()">STOP</button>
      <button (click)="removeAll()">REMOVE ALL</button>
    </div>
    <div class="containerDown">
      <p>{{ display }}</p>
    </div>
  </div>

  <div class="boxRight">
    <div class="containerLeft">
      <ul class="listElementLeft" *ngFor="let item of tasks">
        <div class="card">
          <ul class="order">
            <li class="list-group-item"><span>START:</span>{{ item.start }}</li>
            <li class="list-group-item"><span>END:</span>{{ item.end }}</li>
            <li class="list-group-item">
              <span>LENGTH:</span>{{ item.length }}
            </li>
          </ul>
          <div class="subcard">
            <li>
              {{ item.name }}
            </li>
          </div>
          <div class="buttonCard">
            <button (click)="removeTask(item.id)">REMOVE</button>
          </div>
        </div>
      </ul>
    </div>
  </div>
</div>

TS:

import { importExpr } from '@angular/compiler/src/output/output_ast';
import { Component, OnInit } from '@angular/core';
import { timer } from 'rxjs';
import { Activity } from '../activity';
import { Result } from '../result';

@Component({
  selector: 'app-timer',
  templateUrl: './timer.component.html',
  styleUrls: ['./timer.component.scss'],
})
export class TimerComponent implements OnInit {
  ngOnInit() {
    this.tasks = JSON.parse(localStorage.getItem('token') ?? '');
  }
  time: number = 0;
  display: string | undefined;
  interval: any;
  modalboxActive = false;
  startTime: string | undefined;
  endTime: string | undefined;
  id: number | undefined;

  activity: Activity = {
    name: '',
  };

  tasks: Result[] = [];

  startFunc() {
    this.startTime = new Date().toString().split(' ')[4];
  }

  endFunc() {
    this.endTime = new Date().toString().split(' ')[4];
  }

  //task actions
  addTask() {
    var el: Result = {
      id: this.id!,
      name: this.activity.name,
      end: this.endTime,
      start: this.startTime,
      length: this.display,
    };

    this.tasks.push(el);
    localStorage.setItem('token', JSON.stringify(this.tasks));
    this.activity.name = '';
    this.modalboxActive = false;
    this.resetTimer();
  }

  removeAll() {
    localStorage.clear();
  }

  removeTask(id: number) {
    // this.tasks.splice(id, 1);
    this.tasks = this.tasks.filter((item) => item.id !== id);
  }

  //timer actions
  startTimer() {
    console.log('go');
    this.interval = setInterval(() => {
      if (this.time === 0) {
        this.time  ;
      } else {
        this.time  ;
      }
      this.display = this.transform(this.time);
    }, 1000);
    this.startFunc();
  }

  transform(value: number): string {
    var sec_num = value;
    var hours = Math.floor(sec_num / 3600);
    var minutes = Math.floor((sec_num - hours * 3600) / 60);
    var seconds = sec_num - hours * 3600 - minutes * 60;
    return hours   ':'   minutes   ':'   seconds;
  }

  pauseTimer() {
    clearInterval(this.interval);
  }

  stopTimer() {
    console.log('show');
    this.modalboxActive = true;
    clearInterval(this.interval);
    this.endFunc();
  }

  resetTimer() {
    console.log('reset');
    this.time = 0;
  }
}

Result interface:

export interface Result {
  id: number;
  start: string | undefined;
  end: string | undefined;
  length: string | undefined;
  name: string | undefined;
}

CodePudding user response:

It looks like when you add an item in task list, the task.id is always undefined. You need to give it an unique id in order to identify it on removal.

Try to change the following code:

from:

  ngOnInit() {
    this.tasks = JSON.parse(localStorage.getItem('token') ?? '');
  }

 // task actions
  addTask() {
    var el: Result = {
      id: this.id!, // always is undefined
      name: this.activity.name,
      end: this.endTime,
      start: this.startTime,
      length: this.display,
    };

    this.tasks.push(el);
    localStorage.setItem('token', JSON.stringify(this.tasks));
    this.activity.name = '';
    this.modalboxActive = false;
    this.resetTimer();
  }

  removeAll() {
    localStorage.clear();
  }

  removeTask(id: number) {
    // this.tasks.splice(id, 1);
    this.tasks = this.tasks.filter((item) => item.id !== id);
  }

to:

  ngOnInit() {
    this.tasks = JSON.parse(localStorage.getItem('token')) ?? [];
  }

  // task actions
  addTask() {
    var el: Result = {
      id: this.tasks.length   1,
      name: this.activity.name,
      end: this.endTime,
      start: this.startTime,
      length: this.display,
    };

    this.tasks.push(el);
    localStorage.setItem('token', JSON.stringify(this.tasks));
    this.activity.name = '';
    this.modalboxActive = false;
    this.resetTimer();
  }

  removeAll() {
    this.tasks = [];
    localStorage.removeItem('token');
  }

  removeTask(id: number) {
    this.tasks = this.tasks.filter((item) => item.id !== id); 
    localStorage.setItem('token', JSON.stringify(this.tasks)); // also, update localStorage
  }

You can check a working example here.

  • Related