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

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

所以错误:在ToDoListComponent内部,todoList只初始化过一次,在ngOnInit生命周期挂钩。

解决方案:在addToDo方法中,将值推送到todoService后,再次调用下面的行,

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

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

最新更新