javascript - Xóa hàng khỏi bảng ng-bootstrap
Tôi đã triển khai thành công ví dụ đầy đủ về bảng ng-bootstrap.
Việc xóa đối tượng khỏi DOM và cơ sở dữ liệu đang hoạt động, nhưng tôi không thể tìm cách xóa hàng khỏi giao diện. Để thấy các thay đổi, cần phải tải lại trang. Lưu ý rằng, chức năng xóa đang và nên được kích hoạt từ nút xác nhận trong hộp thoại modal của ng-bootstrap.
Tôi không thể gọi data$ từ vòng lặp for như trong cách dưới đây hoặc tương tự, vì todo (hoặc bất cứ gì) là observable todos$,
<!-- html -->
<tr *ngFor="let todo of tableService.todos$ | async;">
// typescript
deleteRow(id){
for(let i = 0; i < this.data.length; ++i){
if (this.data[i].id === id) {
this.data.splice(i,1);
}
}
}
Ai đó có thể chỉ cho tôi hướng đúng được không, làm ơn.
Tôi có đoạn mã này:
deleteTodo(id: string) {
this.todoService.deleteTodo(id)
.subscribe(data => {
console.log(data); // print message from server
},
error => console.log(error)
);
this.tableService.todoArray = this.tableService.todoArray.filter(elem => elem._id !== id);
this.todoLength--;
this.modalService.dismissAll();
console.log('filtered array: ' + this.tableService.todoArray.length);
console.log('id: ' + id);
}
Chức năng này xóa mục công việc khỏi cơ sở dữ liệu và phương thức lọc xóa công việc khỏi một mảng. Vui lòng xem ảnh chụp màn hình bên dưới.
kho lưu trữ mã nguồn ứng dụng của tôi:
https://github.com/SrdjanMilic/NG-Bootstrap-Todo-list
Câu trả lời #1
Việc phát hiện thay đổi trong Angular không hoạt động với splice vì nó không thay đổi tham chiếu đến biến mảng. Bạn cần hoặc cập nhật tham chiếu biến (ví dụ bên dưới) hoặc kích hoạt phát hiện thay đổi một cách thủ công.
deleteRow(id) {
this.data = this.data.filter(elem => elem.id !== id);
}
Câu trả lời #2
Đây là đoạn mã hoạt động:
todo-list.component.tsexport class TodoListComponent implements OnInit {
todos$: Observable<Todo[]>;
total$: Observable<number>;
@ViewChildren(NgbdSortableHeader) headers: QueryList<NgbdSortableHeader>;
constructor(private todoService: TodoService, private router: Router, private modalService: NgbModal,
public tableService: TableService, public updateTodoComponent: UpdateTodoComponent,
public myBootstrapModalCoomponent: MyBootstrapModalComponent, private ref: ChangeDetectorRef) {
this.todos$ = this.tableService.todos$;
this.total$ = this.tableService.total$;
}
...
deleteTodo(id: string) {
this.todoService.deleteTodo(id)
.subscribe(todo => {
console.log(todo); // print message from server
},
error => console.log(error)
);
this.todos$.subscribe(todos => {
for (let i = 0; i < todos.length; i++) {
if (todos[i]._id === id) {
todos.splice(i, 1);
}
}
});
this.tableService.todoArray.length--;
this.modalService.dismissAll();
}
table.service.ts...
private _todos$ = new BehaviorSubject<Todo[]>([]);
get todos$() {
return this._todos$.asObservable();
}
...
