在Angular中添加/删除/编辑列表项时自动更新视图

问题描述

我正在Angular中做一个待办事项应用程序。现在,我可以使用添加/删除/编辑功能,但是每次都必须刷新网页才能看到更改。

我想要这样,以便一旦添加待办事项列表项,用户就可以自动看到添加到列表中的项目,而不必每次都刷新页面。删除和编辑项目也是如此。

这是我下面的HTML:

<div>
  <input type="text" value={{toDoItem}} [(ngModel)]="toDoItem">
  <button (click)="addToDo()">Add to List</button>
</div>

<div class="items" *ngFor="let todo of todoList">
  <div >
    <input type="checkbox" [(ngModel)]="todo.completed" (change)="updateCompleted(todo.id)">

    <div *ngIf="!todo.editing; else editingTodo">{{ todo.content }}</div>

    <ng-template #editingTodo>
      <input #editVal type="text" value={{updatedItem}} [(ngModel)]="todo.content" >
      <button (click)="onEdit(todo.id,editVal.value)">Save</button>
      <button (click)="toggleEdit(todo.id)">Cancel</button>
    </ng-template>

  </div>

  <div class="remove-item">
    <button (click)="removeTodo(todo.id)">Remove</button>
    <button (click)="toggleEdit(todo.id)">Edit</button>
  </div>
</div>

这是我的打字稿文件,具有以下逻辑:

export class ToDoListComponent implements OnInit{
  @Input()
  todo: Todo;

  toDoItem: string;
  updatedItem: string;
  todoList: Todo[];
  show = false;

  constructor(private todoService: ToDoService) {
    this.toDoItem = '';
    this.updatedItem = '';
  }

  ngOnInit() {
    this.todoList = this.todoService.getTodos();
  }

  addToDo() {
    this.todoService.addTodo(this.toDoItem);
    this.toDoItem = '';
  }

  removeTodo(id: number) {
    this.todoService.removeTodo(id);
  }

  updateCompleted(id: number) {
    this.todoService.updateComplete(id);
  }

  toggleEdit(id: number) {
    this.todoService.toggleEdit(id);
  }

  onEdit(id: number,newContent: string) {
    this.todoService.editTodo(id,newContent);
    this.todoService.toggleEdit(id);
  }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)