我正在查看各种示例并尝试了其中的一些示例,但无法从 UI 级别将其删除。
我尝试使用 *ngFor
。所以 ngFor 只删除了 <span>
,而不是 <buttons>
标签中的 <li>
。然后我尝试建立索引但还没有成功。
<div>
<ul style="list-style-type: none;">
<li *ngFor="let item of todos; let i = index" class="todo-item">
<span [ngClass]="{ inactive: item.done }">{{ item.value }}</span>
<button class="todo-item-button" (click)="editUser()">Edit</button>
<button class="todo-delete-button" (click)="deleteUser(item,i)">Delete</button>
</li>
</ul>
</div>
组件:-
todos: Todo[] = [];
ngOnInit() {
this.todos = this.todoService.getAllTodos();
}
deleteUser(todos ,index: number) {
this.todoService.deleteIndexDb(todos.id)
.subscribe(
() => {
this.todos.splice(index, 1);
});
}
在这方面几乎不需要帮助。
答案 0 :(得分:1)
您需要更改对 todos
数组的引用,以便 Angular 更改检测工作。 Array.splice
不是最佳选择,因为它不会创建新数组。您可以使用 Array.filter
或 Array.map
:
deleteUser(todos ,index: number) {
this.todoService.deleteIndexDb(todos.id)
.subscribe(
() => {
this.todos = this.todos.map((item, i) => {
if (i !== index) {
return item;
}
});
});
}
答案 1 :(得分:1)
使用扩展语法重新分配
deleteUser(todos ,index: number) {
this.todoService.deleteIndexDb(todos.id)
.subscribe(
() => {
this.todos.splice(index, 1);
this.todos = [...this.todos]
});
}
答案 2 :(得分:0)
更改对象类型的值不会触发更改检测,数组在 Javascript 中被视为对象。因此,您需要将 splice 方法返回的新数组分配回 todos 对象,如下所示。
//ES5`enter code here`
this.todos.splice(index, 1);
this.todos = new Array(this.todos);
//ES6
this.todos.splice(index, 1);
this.todos = [...this.todos];