Angular 2 - Refresh interface following deletion

I am facing an issue with my Angular2 app that has a Java backend. I have a list of customers and when I try to remove a customer, the removal is successful but the list does not update automatically. I have tried routing back to the list component within the delete method's subscribe function, but it did not resolve the issue.

list-customers.component.html

<tr [class.warning]="customer.isDefault == 1" *ngFor="let customer of customers | orderBy:['firstName'] | search:searchCustomer.value;let serial = index">
                <td>{{ serial+1 }}</td>
                <td>{{ customer?.firstName+' '+customer?.lastName}}</td>
                <td>{{ customer.email}}</td>
                <td>{{ customer.mobileNumber}}</td>
                <td>{{ customer.streetAddress}}</td>
                <td>{{ customer.priceList?.name}}</td>
                <td><a [routerLink]="['/loggedIn','customer','edit', customer.id ]"><i class="fa fa-edit fa-2x"></i></a></td>
                <td><a (click)="delete(customer)"><i class="fa fa-trash-o fa-2x"></i></a></td>
              </tr>

list-customers.component.ts

    ngOnInit()
    {
        this.refreshCustomersList();
    }

    delete(customer)
    {
        this.userService.delete(customer.id)
            .subscribe(
                success=>
                {
                    var index = this.customers.indexOf(customer, 0);
                    if (index > -1)
                    {
                        this.customers.splice(index, 1);
                    }
                }
            )

    }

    refreshCustomersList()
    {
        this._authHttp.get(
                this.appService.getApiUrl() + "api/customer/list"
            )
            .map(res=>res.json())
            .subscribe(
                successResponse=>
                {
                    this.customers = successResponse.data.customers;
                },
                () => console.log("Request Completed")
            )

    }
}

Answer №1

For an effective solution, make sure to include the this.refreshCustomersList(); function call in your delete method:

    delete(customer)
{
    this.userService.delete(customer.id)
        .subscribe(
            success=>
            {
                var index = this.customers.indexOf(customer, 0);
                if (index > -1)
                {
                    this.customers.splice(index, 1);
                    this.refreshCustomersList();
                }
            }
        )

}

By adding this line of code, you can ensure that the customers array is properly updated when a customer is deleted.

Answer №2

If you want to remove a customer using JavaScript array filter, you can follow this example:

    this.userService.remove(customer.id)
    .subscribe(
        success=>
        {
             let updatedCustomers = this.customers.filter(item => item.id !== customer.id);
             this.customers = updatedCustomers;
        }
    )

Answer №3

Instead of using splice to return the deleted element, switch to slice to retrieve the resulting array after deletion, for example:

this.customers = this.customers.slice(index); 

Answer №4

To implement the code below in HTML, follow these steps:

(click)="delete(customer.length-1-i)".
//
deleteFieldValue(index) {
this.customer.splice(index, 1);
this.revervefordispaly();
}

//for reverse:

revervefordispaly(){
this.reversedProductdata.reverse();
}

Answer №5

I am facing a similar situation where I have an array of products and need to allow users to remove products based on their preferences. If the array becomes empty, I want to display a Cancel button instead of the Back button without refreshing the page.

To achieve this, I checked for an empty array in the ngAfterViewChecked() lifecycle hook.

products: Product[];
someCondition: boolean;

constructor(private cdr: ChangeDetectorRef) {}
// import { ChangeDetectorRef } from '@angular/core';

ngAfterViewChecked() {
    this.checkEmptyArray();
}

checkEmptyArray() {
    this.someCondition = this.products.length === 0 ? true : false;

    // Trigger change detection explicitly
    this.cdr.detectChanges();
}

removeProduct(id) {
    // Logic for removing a product goes here.
}

Answer №6

To avoid re-fetching the entire list from the API, an efficient way to update the customers list is to implement the following method:

removeCustomer(customerToDelete)
{
    this.userService.delete(customerToDelete.id)
        .subscribe(
            success =>
            {
                const index = this.customers.findIndex(cust => cust.id === customerToDelete.id);
                if (index !== -1)
                {
                    this.customers.splice(index, 1);
                }
            }
        );
}

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

Retrieving data from child components within an array in another component using Angular

How can I assign the value of the variable 5 in Array(5) to another variable in this code? My goal: export class HelloComponent { @Input() page: number; active = 0; pages; constructor() { this.pages = Array(this.page) // instead of Array( ...

You are able to set up the booking.com form once but cannot do so again using the ngOnInit method

Currently, I am utilizing angular materials in conjunction with angular4. Within an MdDialogue component, I have embedded HTML code for a booking.com form. The intention is for this dialogue box to appear with the form inside whenever a button is clicked. ...

Exploring the Angular RouterModule within a Java WAR Deployment

In my Angular 6.0.5 application, I leverage Angular's Routing feature to define paths like: http://localhost:8080/area http://localhost:8080/barn http://localhost:8080/tower During development, running the app with ng serve allows me to directly en ...

What is the best way to showcase images in an Angular application when the images are saved in the server uploads folder of a Node.js

In my node.js server, I have a separate directory where I store files in the uploads folder and save image paths in the db. The directory structure looks like this: node_modules src uploads |category-name-folder |image-name.jpg |category-name-folde ...

What is the reason for the nullish coalescing operator failing to function as a typeguard in TypeScript?

Introduced in Typescript 3.7, the nullish coalescing operator seems to be a perfect type guard for scenarios like the following: const fs = (s: string) => s const fn = (n: number) => n let a: string | null | undefined let b: number | null | undefi ...

Exploring the versatility of string types in TypeScript

I'm currently working in React and have an array of pages set up like this. export const pages: Page[] = [ { path: "/", exact: true, component: PageHome }, { path: "/home2", exact: true, component: PageHome2 }, { path: " ...

Achieve form display and concealment with a single click using angular and jQuery, incorporating smooth animations

I am looking to create a button that will show and hide a form. Here is the form I have created : <button type="button" (click)="ShowAndHide()" class="AddCatBtn">show and hide </button> <div class="AddCategory"> <div class="for ...

tying [inactive] to a specific attribute

I have successfully implemented the functionality to disable the button when the email is in the correct format, as shown in my code below. Now, I am looking to implement the following scenario: The Get Started button should be disabled by default If a u ...

The behavior of an Angular 2 method varies depending on whether it is called in ngOnInit or triggered by a button

In the process of constructing a website with the Angular 2 CLI, I have encountered a perplexing issue. Specifically, I am working on a page that features a reactive form and have developed a method named addQuestion() that is invoked within the ngOnInit l ...

Automatically adjust the model input (Signal) based on the parent and respond to any alterations in the children

Within my Angular 16 application, I have a parent component that passes a plain JavaScript object (myObj) to a child component, where it is treated as a model<MyObj>. <!-- parent.component.html --> <app-children [myObjModel]="myObj&qu ...

Tips for navigating the material ui Expanded attribute within the Expansion Panel

After looking at the image provided through this link: https://i.stack.imgur.com/kvELU.png I was faced with the task of making the expansion panel, specifically when it is active, take up 100% of its current Div space. While setting height: 100% did achi ...

What is the method for invoking a component's function that was incorporated through transclusion?

Just starting out with Angular 2, I'm attempting to create a master form that can handle basic functions like resetting and saving. The Master Form utilizes the ng-content directive to load its content area. When the save button is clicked, I want th ...

Leverage RxJs Pipe for transforming Observables into various data types

Currently, I am dealing with an Observable<Recipe[]> that I need to transform into an array of a different class called ChartData[]. This transformed array will be used as a data source for creating highcharts graphs, such as column charts and pie ch ...

Unchanging value in md-select even after selection

Having an issue with the md-select component in Angular Material 2. When I change the value of the select, it updates correctly but the displayed value remains the default "LTC" option. I want to display the currently selected option instead of the default ...

Unable to persist AWS CDK ec2.Instance userData configuration

Trying to launch an ec2 instance with AWS CDK has been successful, but I am struggling to make the userData persistent so it runs on every boot. Despite searching extensively, I couldn't find any documentation on how to achieve this. The code below wo ...

What is the process for initiating an Angular 2 Materialize component?

I'm new to using angular2 materialize and I've found that the CSS components work perfectly fine. However, I'm facing an issue when it comes to initializing components like 'select'. I'm unsure of how or where to do this initi ...

The `message` binding element is assumed to have a type of `any` by default

I am trying to send data from parent component to child component, but I am encountering an error: Binding element 'message' implicitly has an 'any' type. Can someone assist me with my code? const Forms = () => { const [messageTe ...

What is the easiest method for distributing one of my libraries across multiple React Typescript projects?

In my React projects, I often find myself needing to share common data object or utility classes locally. For instance, a utility class that handles detailed string or data structure manipulations. What would be the most effective approach for this? Shoul ...

Enhance your images with the Tiptap extension for customizable captions

click here for image description I am looking to include an image along with an editable caption using the tiptap extension Check out this link for more information I found a great example with ProseMirror, but I'm wondering if it's possible ...

Imitating elegant angular input styles

Just before launch, the higher-ups have decided that they prefer a modern aesthetic for input controls - underlines rather than boxes, with labels that slide out of the way when the input is in focus. Check out the effect on this page: https://material.an ...