Removing information from the app.component.html file in Angular 6 and reflecting those updates in the view

I currently have a service that retrieves a list of data and displays it within the app.component.html.

Below is the code snippet used to display the data:

<ul>
    <li *ngFor="let data of retrieveData"> 
        {{ data.id }} - {{data.title}} <span><button (click)="delete(data.id)">Delete Record</button></span>
    </li>
</ul>

An individual delete button is added to each row of data to trigger a method that removes the data from the server.

While this current setup works, I would like the data to be removed from the view without the page having to be reloaded.

In the app.component.ts file, the method below is used to call the service method:

delete() {
    this.apiService.delete(1).subscribe(result => {
      console.log(result);
    }, error => console.log('There was an error: ', error));
}

What is the best way to ensure the component data is updated without requiring a page reload?

Answer №1

Remove the deleted element from the displayed collection.

delete(id) {
    this.apiService.delete(id).subscribe(result => {
      console.log(result);
      this.repopulateData = this.repopulateData.filter((elem) => {
          return elem.id !== id;
      });
    }, error => console.log('An error occurred: ', error));
}

Answer №2

To begin, locate the position of the item that needs to be removed from the dataset. Once it has been successfully identified, proceed to delete it from the existing list of items.

eliminate(passedIdentifier) {
    this.requestService.remove(passedIdentifier).subscribe(outcome => {
      console.log(outcome);
      let positionOfIdentifier = this.obtainInformation.findIndex((element) => {
          return element.id === passedIdentifier;
      }); //provides the index of the first match
         // assuming that each id is unique
      this.obtainInformation.splice(positionOfIdentifier, 1);  // deletes the specified element
                                              // from the list that was previously loaded
      this.obtainInformation.someFunction()
    }, failure => console.log('An error occurred: ', failure));
}

Answer №3

To effectively delete an item using ngFor, simply pass the index to your delete() function as shown below:

<ul>
    <li *ngFor="let data of retrieveData; let idx = index"> 
        {{ data.id }} - {{data.title}} <span><button (click)="delete(data.id, idx)">Delete Record</button></span>
    </li>
</ul>

Then, within your delete function:

delete(id, idx) {
  this.apiService.delete(id).subscribe(result => {
    console.log(result);
  }, error => console.log('Encountered an error: ', error));
  this.retrieveData.splice(idx, 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

What is the most effective way to update the React state based on an if-else condition within a

I am facing an issue where I have a component in my project that needs to update the parent state when clicked, but there is an if-else condition causing the state not to update in the parent component. In my project, I have two boxes with an if-else cond ...

Animating a progress bar with JQuery

Having issues with displaying a progress bar using jquery and javascript, as it is not appearing on the page. var show_time = Math.floor(Math.random() * 10000) + 5000; setTimeout(function() { $("#progress").hide() }, show_time); var myCountdown = $( ...

Dnd-kit: item loses its place in line when dragged over Droppable area

I've encountered an issue while using @dnd-kit. The sorting function works smoothly (e.g. when I drag the 1st element, it sorts correctly), but once I reach a droppable element (green Thrash), the sorting breaks and the 1st element snaps back. You ca ...

Sharing a let value within *ngFor loop from template to .ts file - here's how

Is it possible to use the async pipe to share the interpolation value {{ticketType.name}} with the .ts component in order to work with this value efficiently? Here is a sample of the template code: <mat-option *ngFor="let ticketType of ticketTypes ...

A useful tip for jQuery users: learn how to prevent the context menu from appearing when a text box is

Is there a way to prevent the context menu from appearing in jQuery when the text box is disabled? The right-click disable functionality works well in all browsers except for Firefox. Please note that the right-click disable functionality works when the t ...

Guide on initiating document-wide events using Jasmine tests in Angular 2/4

As stated in the Angular Testing guidelines, triggering events from tests requires using the triggerEventHandler() method on the debug element. This method accepts the event name and the object. It is effective when adding events with HostListener, such as ...

Getting files from CDN using NuxtJS content module - a beginner's guide

Is there a way to fetch files from an external server, such as a CDN, using the @nuxtjs/content module? This would allow me to manage the .md files independently without relying on Nuxt.js. In my current nuxt.config.js file, I have the following setup: ex ...

Top Bootstrap Div with Sticky Scrolling Fixation

Trying to implement sticky-top from bootstrap to fix a div when scrolling. Implementing as follows: <div class="col-md-4"> <div class="sticky-top"> <app-reserva></app-reserva> </div> </div> Various sources sug ...

The ng-model does not reflect changes when using the JQuery datepicker

Currently, I have set up two textboxes for users to choose a date. I am utilizing JqQuery's datepicker UI to showcase a small calendar pop-up whenever the user clicks on the textbox. However, an issue arises when I select a date in the calendar popup ...

The Appsheet algorithm determined the exact expiration date as 2 days from the specified date

In my Appsheet, I have two columns: Production Date and Expired Date. If the Production Date is 35 months before the Expired Date, how can I create a formula in Appsheet to calculate this? For example, if the Production Date is 01/10/2023, then the Expired ...

What is the best way to extract information from an observable stream?

Within my codebase, there exists an observable that I have defined as: public selectedObjectsIds$ = of(); In addition, there is another stream present: this.reportMode$.pipe( filter((state: ReportMode) => state === ReportMode.close) ) .subscribe(() ...

How to prompt a nested function to refresh in Angular by using a force

As a newcomer to Angular(1.x), I am currently integrating it into the app I am working on. The app fetches user data via ajax, which includes multiple nested arrays, and then displays them using nested ng-repeat directives. Within the innermost repeat, I h ...

Eliminate item from array based on certain criteria

In certain scenarios, I must update the filters. Under specific data conditions, I am required to eliminate 1 item from an array. Here is the code snippet: useEffect(() => { let canceled = false; const filters = [ new C ...

Issue with datepicker functionality not operational for newly added entries in the table

@Scripts.Render("~/bundles/script/vue") <script> var vueApp = new Vue({ el: '#holiday-vue', data: { holidays: @Html.Raw(Json.Encode(Model)), tableHeader: 'Local Holidays', holidayWarning: true, dateWarning: true }, methods: ...

I am feeling quite lost in trying to figure out how to create a voice mute command using Discord

I've been searching for information on how to create a command that mutes only one specific person I tag in chat, but I'm having trouble finding any guidance on it. As someone new to discord and node js, I could really use some assistance. Mute ...

Angular auto-suggest components in material design

Can someone assist me in resolving my issue? I am trying to incorporate an autocomplete feature with a filter into my form. .ts file : contactArray; selectedContact: IContact; myControl = new FormControl(); filteredContact: Observable<string[] ...

guide to setting up router access using token

I've received a token from the backend axios.post(process.env.VUE_APP_LOGIN, payload) .then(response => { const {access_token, token_type, user} = response.data; this.token = access_token this.$store.commit(&a ...

Enhance jQuery for a dynamic navigation dropdown with multiple sub-menus

Looking for help with a jQuery script as I am a beginner in using jQuery. jQuery(document).ready(function ($) { $(".sub-menu").hide(); $(".current_page_item .sub-menu").slideDown(200);; $("li.menu-item").click(function () { if ($('.sub-menu&apos ...

Issue encountered while parsing JSON file using AngularJS

Having some trouble reading a json file in AngularJS using $http.get and encountering errors in the browser console. Check out my Plunker example: http://plnkr.co/edit/SDRpu1MmrTPpgpdb6Kyk?p=preview Below is the code snippet: Javascript:- var jayApp = ...

Is it possible to manipulate a parent component's state with a child component?

I have been experimenting with Material UI's react modal to create a modal as my child component. In the parent component, I have set up a state that controls the visibility of the modal and added a button inside the modal to close it. However, this s ...