Deleting items from a JavaScript object array in Angular using TypeScript can be achieved by using various methods and

Here is the structure of my object array:

0: {Name: "Albert", Id: 32}
1: {Name: "George", Id: 34}
2: {Name: "Jane", Id: 35}

Although the request is successful, the array remains unchanged. However, upon refreshing the app, the item (student) is deleted. When I attempt to delete by clicking the button, I receive the following error: INDEX:-1

What could be the issue here?

student.component.html

<thead>
<tr style="font-weight: 500;font-size:15px;">
  <th data-field="id">Id</th>
  <th data-field="name">Display Name</th>
  <th>Delete</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let student of students;">
  <td>{{ student.Id }}</td>
  <td>{{ student.Name }}</td>
  <td><span class="ion-android-delete" (click)="onDelete(student.Id)"> </span></td>
</tr>
</tbody>

student.component.ts

onDelete(studentId: number) {
    if (window.confirm('Are you sure you want to delete?')) {
      var index = this.students.indexOf(studentId, 1);
        while (this.students.indexOf(studentId) !== -1) {
        this.students.splice(this.students.indexOf(studentId), 1);
      }

      this.studentService.deleteStudent(studentId)
        .subscribe(
        (response) => console.log(response));
        (error) => console.log(error));
    }
}

student.service.ts

deleteStudent(studentId: number) {    
  return this.http.delete......

            (response: Response) => {
                const data = response.json();
                return data;
            }
            )
            .catch(
            (error: Response) => {
                console.log(error);
                return Observable.throw(error);
            }
            );
}

Modified code snippet:

 onDeleteAgent(agentId: number) {
    if (window.confirm('Are you sure you want to delete?')) {

      while (this.agents.indexOf(this.agents) !== -1) {
        console.log(this.agents.indexOf(this.agents));
        this.agents.splice(this.agents.indexOf(this.agents), 1);
      }

      this.agentService.deleteAgent(agentId)
        .subscribe(
        (response) => console.log(response),
        (error) => console.log(error));
    }
  }

Answer №1

It seems like there are some improvements that can be made to your onDelete method. If you need to begin from the studentId, consider implementing the following changes:

onDelete(studentId: number) {
  if (!window.confirm('Are you sure you want to delete?')) {
    return;
  }

  var student = this.students.find(s => s.Id === studentId);
  var index = array.indexOf(student);

  if (index > -1) {
    array.splice(index, 1);
  }
}

Alternatively, you can simplify the process by filtering the array like this (just make sure you can reassign the array without any complications):

onDelete(studentId: number) {
  if (window.confirm('Are you sure you want to delete?')) {
    this.students = this.students.filter(s => s.Id !== studentId);
  }
}

Answer №2

student.component.html

<thead>
<tr style="font-weight: 500;font-size:15px;">
  <th data-field="id">Identification</th>
  <th data-field="name">Name to Display</th>
  <th>Remove</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let student of students;let i = index">
  <td>{{ student.Id }}</td>
  <td>{{ student.Name }}</td>
  <td><span class="ion-android-delete" (click)="onDelete(student.Id,i)"> </span></td>
</tr>
</tbody>

student.component.ts

onDelete(studentId: number,index) {
    if (window.confirm('Are you sure you wish to remove this item?')) {
        this.students.splice(index, 1);    
      this.studentService.deleteStudent(studentId)
        .subscribe(
        (response) => console.log(response));
        (error) => console.log(error));
    }
}

Answer №3

Within the student.component.ts file, the Delete method needs to be corrected as there is a mismatch between the student id and the object Array. Below is a simplified version of the delete method which follows good practices by deleting the object after receiving a response from the server.

onDelete(studentId: number) {
    if (window.confirm('Are you sure you want to delete?')) {      

      this.studentService.deleteStudent(studentId)
        .subscribe(
        (response) => {
             for(let i=0;i<this.students.length;i++){
               if(this.students[i].Id == studentId){
               this.students.splice(i,1);
                break;
             }
        });
        (error) => console.log(error));
    }
}

Answer №4

To delete a student, you can simply apply the filter method and remove the student from the list by creating a new object reference using the spread operator with this.students.

onDelete(studentId: number) {
  if (window.confirm('Are you sure you want to delete?')) {
    this.students = [...this.students.filter((student:any) => student.Id !== studentId)];
  }
...

Remember: While the spread operator is optional, it is a good practice to use it for creating immutable objects.

Alternative method without the spread operator:

this.students = this.students.filter((student:any) => student.Id !== studentId);

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 could be causing the absence of data from my API on my HTML page?

I've been working on fetching data from my database using an API in Angular, but I'm facing an issue where the data is not being displayed on the HTML component. Although I can see that the data is being fetched through the console and the HTML p ...

"Although the NextJS client-side data is present, it seems to be struggling to

I am facing an issue while trying to display fetched data on a blog page. Although the data is successfully retrieved client-side and I can view it using console.log(), it does not appear on the page and the elements remain empty. I am completely puzzled. ...

Sending print jobs to an HTTP printer from an HTTPS connection using Angular 6

Currently, I have an Angular 6 application set up with Nginx and HTTPS. However, I am facing an issue when trying to send commands to my ZPL printer for label printing. The problem lies in the fact that the printer only accepts HTTP protocol, but the brows ...

Steps for downloading Excel or Zip files in Angular 4

Currently, my front end is built using Angular 4 and the back end is developed with Lumen 5.4. The task at hand requires me to export certain data as both an Excel and a zip file. I am utilizing the { saveAs } import from the package 'file-saver/Fil ...

Error: An unexpected character (.) was encountered | Building with npm has failed

When executing "npm run build", I encounter an error with the unexpected token (.) related to object values. Can someone assist me in resolving this issue? I am using tsc build for a react npm library. It seems like there might be a configuration problem ...

What is the best way to access object IDs from Firebase and then save them individually?

I'm currently developing an Ionic application using the Angular framework. In order to remove objects from Firebase's real-time database, I need the ID of each object. Despite being a beginner in this field, I have not been able to find a solutio ...

"Python - Exploring the World of Array Slicing

I have been given an assignment by my university to analyze a specific slicing operation. A = array([[1,2,3],[4,5,6],[7,8,9]]) A[0,arrange(3)<>0] A[1,arrange(3)<>1] A[2,arrange(3)<>2] The operation in question is A[k, arange(n)<>k ...

Error message TS2339: The method 'findAll' is not defined in the current context

Despite following the Sequelize guide for TypeScript configuration, I am unable to resolve an issue with my database connection. The connection is active, but I am struggling with a specific type problem: TSError: ⨯ Unable to compile TypeScript: controll ...

Expanding the base class and incorporating a new interface

(Here is an example written using Typescript, but it applies to other cases as well) class IMyInterface { doC:(any) => any; } class Common { commonProperty:any; doA() { } doB() { } } class ClassA extends Common {} class Clas ...

Enabling a JSON file property to be clickable as needed

I am working with a JSON file obtained from an API call, which contains various objects. My goal is to display the message property of each object, some of which may contain hyperlinks within the message. Here is the HTML code I have implemented to make t ...

Issue: Unable to find Store provider while using @ngrx/store in Angular 4.0

Issue: Error: No provider for Store! I am trying to initialize the store module in main.ts: platformBrowserDynamic().bootstrapModule(AppModule,[ provideStore({ characters, vehicles }) ]); Then I am injecting it into vehicle.component.ts: c ...

Issue: formGroup requires an input of type FormGroup. Please provide one; Error: Unable to access property 'controls' as it is undefined

In the process of building a login and registration form using Angular with .Net core, I encountered an error upon running the program. The error is showing up in the Browser Console tab. This is my userlog.component.ts file: import { Component, OnInit, O ...

To continue receiving rxjs updates, kindly subscribe if the specified condition is met

Is there a way to check a condition before subscribing within the operator chain? Here's what I have: // parentElem:boolean = false; // the parent elem show/hide; let parentElem = false; // inside the ngAfterViewInit(); this.myForm.get('grandPa ...

Is TypeScript failing to enforce generic constraints?

There is an interface defined as: export default interface Cacheable { } and then another one that extends it: import Cacheable from "./cacheable.js"; export default interface Coin extends Cacheable{ id: string; // bitcoin symbol: stri ...

Searching for true values in MongoDB using the query syntax can be challenging

I have a question that might be a bit embarrassing, but I need help with rendering a user search based on both location and date. Our profile object is structured like this: availability: { monday: { type: Boolean, default: false }, tuesday: { type ...

What is the process for eliminating a field from an Angular Reactive Form?

I am working with an Angular form that needs to be sent to the API and it includes 4 fields: username, email, password, and confirmpassword. However, I only want to send three of them - username, email, and password. Does anyone have any suggestions on ho ...

Differentiating elements from two array objects in typescript: a guide

I am facing an issue in extracting the different elements from two array objects. Here is my example: array1 = [{id: 1, a: "a", b: "b"}, {id: 2, c: "c", d: "d"}, {id: 3, e: "e", f: "f"}]; array2 = ...

Tips for adding a time increment of 24 hours to a date variable in Angular 6

My goal is to update a date variable called EndDate stored in localStorage by adding exactly 24 hours to it. The current value in the localStorage is Sun Jun 09 2019 20:39:44 GMT+0530 (India Standard Time). var endDate = new Date(); endDate.setDat ...

What is the best way to configure distinct proxy and backend API URLs for development and production environments?

My goal is to seamlessly link an Angular / C# Web Api project on localhost while developing. For this, I typically use the following URL in the Angular app: http://localhost:5000/api/something However, this setup does not work once deployed. Ideally, I w ...

What could be the reason for the unavailability of this.state in this particular situation?

In my component, I have defined the following functions: constructor(MyProps: Readonly<MyProps>){ super(MyProps); this.state = {suppliers: [], supplierId:0, supplierName:''}; this.addSupplier.bind(this); } addSupplier(){ ...