Remove a row from an ng-bootstrap table

I've managed to successfully implement the ng-bootstrap table full example.
Deleting objects from the DOM and database works fine, but I'm struggling to figure out how to delete a row from the view without having to reload the page. It's important to note that the delete function needs to be triggered from the ng-bootstrap modal dialog confirm button.

I can't access data$ from the for loop like in the example below or similar approaches, because todo (or whatever name) is an 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);
    }
  }
}

Can someone please guide me in the right direction?

I have this piece of code:

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

This function removes a todo item from the database, and the filter method removes the todo from an array. Please refer to the screenshot below.

https://i.sstatic.net/GPGYR.png

Link to my app's source code repository:
https://github.com/SrdjanMilic/NG-Bootstrap-Todo-list

Answer №1

Angular's mechanism for change detection does not recognize changes made by the splice method because it does not alter the reference to the array variable. To ensure that changes are detected, you must either update the variable reference as shown in the example below or manually trigger the change detection process.

removeItem(index) {
   this.items = this.items.filter(item => item.index !== index);
}

Answer №2

Here is the functioning code snippet:

task-list.component.ts

export class TaskListComponent implements OnInit {
  tasks$: Observable<Task[]>;
  total$: Observable<number>;

  @ViewChildren(NgbdSortableHeader) headers: QueryList<NgbdSortableHeader>;

  constructor(private taskService: TaskService, private router: Router, private modalService: NgbModal,
              public tableService: TableService, public updateTaskComponent: UpdateTaskComponent,
              public myModalComponent: MyModalComponent, private ref: ChangeDetectorRef) {
    this.tasks$ = this.tableService.tasks$;
    this.total$ = this.tableService.total$;
  }

...

deleteTask(id: string) {
  this.taskService.deleteTask(id)
    .subscribe(task => {
      console.log(task); // print message from server
    },
      error => console.log(error)
    );
  this.tasks$.subscribe(tasks => {
    for (let i = 0; i < tasks.length; i++) {
      if (tasks[i]._id === id) {
        tasks.splice(i, 1);
      }
    }
  });
  this.tableService.taskArray.length--;
  this.modalService.dismissAll();
}

table.service.ts

...
private _tasks$ = new BehaviorSubject<Task[]>([]);

get tasks$() {
  return this._tasks$.asObservable();
}
...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for transferring JSON information from a perl script to an angular controller on a local level

Summary: I am looking for a way to utilize a service similar to Angular's http service, but locally on my machine without the need for a server to be running. Currently, I am encountering this error message: Access to XMLHttpRequest at 'file:C:/ ...

Exposing the secrets of the Ajax module

Here is the code snippet I am working with: my.data = function () { var getAuth = function (userName, password) { var model = JSON.stringify({ "UserName": userName, "Password": password }); var result; $.ajax({ url: m ...

What is the reason behind this being deemed as true?

Imagine we have this snippet of code: var attachRed = false; Why is attachRed = !attachRed equivalent to true? I'm curious because I'm working with Vue.js and trying to grasp why this particular piece of code functions as it does. <div id= ...

Scroll-triggered animation of SVG paths in React

While achieving this in vanilla Javascript is relatively simple (check out this for an example), I'm encountering difficulties implementing it in React, especially with a library like Framer Motion for animations. Framer Motion's useViewPortScro ...

What is the best way to transfer information within the same webpage?

https://i.sstatic.net/umfln.pnghttps://i.sstatic.net/9W6ZE.pngI'm just starting out with angular 2/4 projects and I have a popup search tab in the interface that displays an editable list. However, I am unsure about how to transfer data to the main i ...

Revamping the Look: Refreshing Background of Div

I'm attempting to change the background image of the body element on a webpage when I hover over links with data-* attributes. It's working perfectly, but I can't seem to figure out how to create a smooth fade between the images when a link ...

Conceal the div class upon clicking it

I'm dealing with a list of videos and I need to hide the class when it's clicked. Check out this sample HTML output: <div id="primary-video"> <iframe id="video" width="100%" height="auto" src="https://www.youtube.com/embed/test" fra ...

Prevent the display of list elements upon clicking by utilizing Angular's Observable and async features

My search bar allows users to enter characters, and through Angular Observable with HTTP GET, they receive suggestions for similar keywords. When a user clicks on a suggestion, it populates the search form with that keyword. The issue is that even after s ...

Place the second division beneath the first within a single navigation bar that adjusts accordingly to all screen sizes

I am experiencing an issue with the layout of my page that has 2 divs within one nav element. When the screen width is greater than 1024px, everything looks fine. However, when I reduce the width to less than 768px, the two divs merge into one line instead ...

Struggling with filtering an array fetched from an API using VueJS

Currently, I am working on a Nativescript-Vue app and facing some challenges that I need help with. The Scenario I have data coming in from an API. Here is the structure of the data I receive: { "count": 9, "results": [ { "id": 1, "c ...

Ways to populate dynamic choices for multiple Select boxes within an ng-repeat loop

When I click the "Add Row" button on an Html form, dynamic rows are added. Each row contains a 'Country' select and a 'State' select. The issue I am facing is that when I select a country in one row, all other row values change as well. ...

Display issues with deeply nested components

I'm facing an issue with displaying the third nested component. Expected: Hello App Component Hello Nest-A Component Hello Nest-1 Component Hello Test-Z Component Actual: Hello App Component Hello Nest-A Component Hello Nest-1 Component Why ...

Utilizing Express.js for reverse proxying a variety of web applications and their associated assets

I am looking to enable an authenticated client in Express to access other web applications running on the server but on different ports. For instance, I have express running on http://myDomain and another application running on port 9000. My goal is to re ...

In my Vue watch method, I have two parameters specified, and one of them remains constant without any changes

Currently, I am attempting to access a method within my watch function with two parameters. Here is the code snippet for the method: onBoolianChange(value, willChange) { willChange = (value === false) ? true : false; }, watch: { "e ...

Looking to verify the validity of my email and phone number

Looking for some assistance in validating my email and telephone inputs for the contact form. The current code for email validation is incorrect, so I need help fixing it. It should be something like this: if(email.length == 0 || email.indexOf('@&apo ...

Express: utilizing rawBody or buffer for a specific endpoint

I am looking to access the rawBody (buffer) specifically for a POST request on one route within my application. Currently, I have the following code snippet in my app.js: app.use(bodyParser.json({ verify: function(req, res, buf) { req.rawBody = buf; }})) ...

Issue with Mongoose $in operator causing updates to only affect a single document

Having some issues with the "$in" operator in Mongoose. I have a User schema that includes an array of Card schema. The Card schema contains a 'score' field that I want to update based on a list of Card ids. Here's what I have attempted: Us ...

Loading JSON data into HTML elements using jQuery

I am currently grappling with coding a section where I integrate data from a JSON file into my HTML using jQuery. As a newbie to jQuery, I find myself at a standstill. https://jsfiddle.net/to53xxbd/ Here is the snippet of HTML: <ul id="list"> ...

What is the best way to set a button as the default option when it is pressed down?

<div class="input-group"> <input type="text" id="srcSchtext" class="form-control" runat="server" placeholder="Search here..." /> <span class="input-group-btn"> <asp:Button runat="server" ID="btnSearchEmployee" ...

Exploring the benefits of useContext in Expo router

Currently, I am working with the latest Expo-Router version which incorporates file-based navigation. To establish a universal language context in my application, I have utilized React's context API along with the useReducer hook. However, I am encoun ...