【问题标题】:Automatically updating the view as a list item is added/deleted/edited in Angular在 Angular 中添加/删除/编辑列表项时自动更新视图
【发布时间】:2020-12-05 07:14:00
【问题描述】:

我正在 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);
  }
}

【问题讨论】:

    标签: javascript html angular binding


    【解决方案1】:

    基本错误是组件没有维护状态,而不是 todoService。

    所以错误:ToDoListComponent 内部的 todoList 只在 ngOnInit 生命周期钩子中初始化了一次。

    解决方法:在 addToDo 方法中,将 value 推送到 todoService 后,再次调用下一行,

    this.todoList = this.todoService.getTodos();  
    

    更新和删除也应该这样做,以查看这些操作所反映的更改。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-13
      • 2016-07-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多