首页 > 解决方案 > 如何从 Angular 的任务列表中删除项目?

问题描述

我正在创建一个调度程序,我可以在其中添加我在一定时间内完成的任务。任务以类似待办事项列表的方式添加。

我正在尝试从前端和 LocalStorage 的列表中删除单个项目,但我还没有找到可行的解决方案。我正在尝试使用的功能是“RemoveTask()”。这是我的代码:

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

结果界面:

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

标签: htmlangulartypescript

解决方案


看起来当您在任务列表中添加项目时,task.id 始终未定义。您需要给它一个唯一的 id 以便在删除时识别它。

尝试更改以下代码:

来自

  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);
  }

至:

  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
  }

您可以在此处查看一个工作示例。


推荐阅读