Tips for updating mfData in Angular 4 after deleting information from it

I have integrated mfDataTable into my UI to display data in a tabular format. Each row in the table has a button that allows users to remove the corresponding row. While I am able to successfully remove the data from the array in the component, the table does not refresh automatically. Below is the relevant code snippet where I request your guidance on identifying any errors and refreshing only the table on the UI:

The usage of mfDataTable is included below:

import { DataTableModule } from "angular2-datatable";

Here's the Service class containing fixed data:

@Injectable()
export class AgentsService {
  agentsData = [{
    'id': 1,
    'agentCountry': 40,
    'agentName': 'New Agent',
    'agentNumber': 246
  },
   {...more agents...}
  ];

  removeAgentByAgentId(agent: any): void {
    let index: number = this.agentsData.indexOf(agent);
    if (index !== -1) {
      this.agentsData.splice(index, 1);
    }
  }
}

This snippet demonstrates the HTML part defining the table using mfDataTable:

<table class="table table-striped" [mfData]="agentsData | agentsDataFilterByCountry : filterByCountry" #mf="mfDataTable" [mfRowsOnPage]="rowsOnPage"
    [(mfSortBy)]="sortBy" [(mfSortOrder)]="sortOrder">
    <thead>
        <tr>
            <th style="width: 15%">Actions</th>
            <th style="width: 20%">
                <mfDefaultSorter by="agentName">Name</mfDefaultSorter>
            </th>
            <th style="width: 5%">
                <mfDefaultSorter by="agentNumber">Number</mfDefaultSorter>
            </th>
            <th style="width: 10%">
                <mfDefaultSorter by="agentCountry">Country</mfDefaultSorter>
            </th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let agent of mf.data; let i = index" [attr.data-index]="i">
            <td>
                <button (click)="onDeleteConfirm(agent)" class="btn btn-danger ion-trash-a"></button>
            </td>
            <td>{{agent.agentName}}</td>
            <td>{{agent.agentNumber}}</td>
            <td>{{agent.agentCountry}}</td>
        </tr>
    </tbody>
</table>

In the Component, I have implemented the OnChanges but I am not receiving any logs from the ngOnChanges method, which indicates that the data table is not being refreshed:

import { Component, OnInit, OnChanges, SimpleChange, Input } from '@angular/core';
import { AgentsService } from '../../services/agents/agents.service';

@Component({
  selector: 'app-agents',
  templateUrl: './agents.component.html',
  styleUrls: ['./agents.component.scss']
})
export class AgentsComponent implements OnInit, OnChanges {

  private service: AgentsService;
  agentsData: Array<any>;
  filterByCountry = "40";
  rowsOnPage = 10;
  sortBy = "agentName";
  sortOrder = "asc";

  constructor(service: AgentsService) {
      this.service = service;
      this.agentsData = service.agentsData;
  }

  ngOnInit() {
  }

  ngOnChanges(changes: {[propKey: string]: SimpleChange}) {
    console.log("something changed");//not logging anything... :(
  }

  onDeleteConfirm(agent: any): void {
    if (window.confirm('Are you sure you want to delete?')) {
      console.log("agentsData before remove: "+this.agentsData.length);
      this.service.removeAgentByAgentId(agent);
      this.agentsData = service.agentsData;
      console.log("agentsData after remove: "+this.agentsData.length);
    }
  }
}

Although the log within the onDeleteConfirm method confirms successful removal of the selected agent, the table is not refreshed accordingly. Could you provide guidance on how to trigger a refresh? Thank you!

Answer №1

To optimize your collection, consider using the code snippet below in your component:

this.agentsData = new Array<any>();
this.agentsData = this.service.getAgentData();

Make sure you have created a getter method in your service before incorporating the above code.

Alternatively, you can achieve the same result by using:

this.agentsData = new Array<any>();
this.agentsData = this.agentsData.concat(this.service.agentsData);

Both methods will yield similar outcomes.

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

Exploring Style Attribute Manipulation using vanilla JavaScript on Firefox

I searched for a similar question, but I couldn't find anything quite like it. I'm currently developing a JavaScript Slider plugin for various projects within our company. This requires me to manipulate styles on certain elements in the DOM. I&a ...

Switching the website address after picking an option from the drop-down menu

I have an HTML form that includes two dropdown menus. The first dropdown is populated from a database using PHP, and the second dropdown is linked to the first one and uses AJAX to update its values based on the selection from the first dropdown. My goal ...

Communicate through Node.js, with messages that multiply based on the total number of users currently in the chat room

Currently, I am working on a project that involves creating a chat application using Node.js. However, I have run into an issue where the message gets repeated for each user in the chat. For example, if there are 4 users in the chat, the message will be di ...

Accessing deeply nested objects from props

After pulling an object from my MongoDB database with Redux and passing it as props to a component, I am facing an issue where I can see the object in the console log but cannot access any information within the object. My objective is to extract specific ...

Creating a <p-table> with a sleek grey header

Trying to figure out how to make the table header grey in an Angular p-table. I have been using ng-template, but it seems like I might be missing something. Here's what I have: <p-table> <ng-template pTemplate="header" let-rowDat ...

How can I retrieve the precise location of a loaded .obj file in three.js?

When trying to load the .obj file: loader.load( 'test.obj', function ( objMesh ) { objMesh.traverse( function ( child ) { if ( child instanceof THREE.Mesh ) { child.material = mat2; ...

The error message "TypeError ".deploy" is not a function in your Hardhat environment."

Currently, I'm in the process of developing a page for minting NFTs called astro-mint. To move forward, I need to deploy my contract using hardhat. However, when I execute this command npx hardhat run scripts/deploy.js --network dexitTestnet An erro ...

Ensure that it is safe to bypass Vue's built-in sanitization on this specific Vue component for the href attribute

I encountered an issue with a .vue file that contains an anchor tag as shown below: <a class="login_class" :href="loginUrl">Use Universal Login</a> When running Sonar, it raises a warning regarding the :href attribute: En ...

Tips on converting comma-separated values into HTML table rows using <tr> tags

JSON Data { "catalog_name": ["Sistem Autodownline ", "Karipap Pusing Ayu"], "price": ["100", "8"], "qty": "", "qty2": ["", ""], "total_qty": "", "total": "", "mem": "10", "email_2": "", "ic_add": "890527-08-6136", "c ...

How to enhance mouse tracking beyond browser window boundaries in Three.js and across various page elements

I'm facing an issue with my three.js scene where I have buttons positioned on top and off to the side of the scene. When you click and drag to spin the camera, the spinning stops when dragging over the buttons or outside the window. I am using three.j ...

Angular with Ionic v4 - Creating custom directives for input elements

Seeking to develop a new function akin to the "clearInput" directive found on the ion-input component, with a different icon and enhanced features :) Previously had a directive functioning in ionic 3, but now it's no longer within the shadow dom elem ...

Utilizing exponential formatting for Plotly axis scales

Following up on a previous question here: SO Q The solution provided in the previous question uses JavaScript code to convert axis ticks into exponential format, but it only works for a single axis on a single plot. When applied in a subplot() structure, ...

Tips for identifying and logging out a dormant user from the server side using Angular 2 Meteor

I'm currently diving into Angular 2 Meteor and working on a project that requires logging out the user when they close their browser window. I also need them to be redirected to the login page when they reopen the app. After searching online, I could ...

Building React applications with server-side rendering using custom HTML structures

I recently started using Suspense in my React app and decided to implement SSR. However, as I was going through the documentation at https://reactjs.org/docs/react-dom-server.html#rendertopipeablestream, I couldn't find a clear explanation on how to u ...

Including folders recursively using Node.js

Currently, I am in the process of setting up test automation using yarn, selenium, and node js. In the wdio.conf.js configuration file, there is a requirement to specify a specs array that contains strings representing paths to various js files for executi ...

Importing d3.JS JSON data without polluting the global scope

Here is a JSON object: { "temp_data": [10,15,20] } I'm trying to import it: var temp_data; //Importing from JSON if(true){ d3.json("graph.json", function(error, graph) { if (error){ throw error; } temp_da ...

Exploring Angular Components with Jasmine and Karma while integrating third-party tools such as ExcelJS

Currently tackling the challenge of writing tests for a project using ExcelJS. The project runs smoothly in both build and production environments, but when attempting to incorporate unit tests for certain components, I'm encountering issues with Test ...

Body Parser causing unexpected output

Currently encountering an issue when attempting to log the body of a POST request in my console. Despite seeing the payload in my Chrome console with the correct data, I am receiving the following error: express_1 | TypeError: Cannot read property ' ...

Is it possible to transform this nested promise into a chain instead?

This situation is just a scenario | then (items) | then (items, actions) getItems() | getActions(for:items) | apply(actions -> items) :promise | :promise | model <= items | | :sync ...

Tips for making a sidebar sticky when scrolling

In order to keep the right-side bar fixed, I have implemented this javaScript function: <script type="text/javascript> $(document).ready(function () { var top = $('#rightsidebar-wrapper').offset().top - parseFloat($('#rightsideb ...