The deletion of property '1' from the [object Array] is not possible

How to Retrieve a List in My Components Using Input :

@Input() usersInput: Section[];

export interface Section {
    displayName: string;
    userId: number;
    title: number;
}

Here is the Value List :

    0:
     displayName: "بدون نام"
     firstName: null
     lastName: null
     title: 0
     userId: 1
   1:
     displayName: "محمدامین چهاردولی"
     firstName: "محمدامین"
     lastName: "چهاردولی"
     title: 0
     userId: 2

In ngAfterViewInit, I assign the input value to the Users List:

ngAfterViewInit(): void {
    this.users = this.usersInput;
    if (this.users.length === 0) {
        this.show = false;
    } else {
        this.show = true;
    }
}

This is the Users List:

users: Section[] = []; And it is used in an HTML list:

<div *ngFor="let item of users" class="d-flex selected-list-items mt-3">
    <div class="col-md-5 col-lg-5 col-xs-5 col-sm-5 col-xl-5">
        <label>{{item.displayName}}</label>
    </div>
    <div class="col-md-5 col-lg-5 col-xs-5 col-sm-5 col-xl-5">
        <label> {{ getEnumTranslate(item.title)}}</label>
    </div>
    <div class="justify-content-center col-md-2 col-lg-2 col-xs-2 col-sm-2 col-xl-2">
        <button (click)="deleteUser(item.userId)" mat-button>
            <mat-icon aria-label="Delete" color="accent">delete</mat-icon>
        </button>
    </div>
</div>

When trying to use the delete button, I encounter the following issue:

  <button (click)="deleteUser(item.userId)" mat-button>
       <mat-icon aria-label="Delete" color="accent">delete</mat-icon>
  </button>

In the TypeScript file:

    deleteUser(id: number): void {
    let userModel = {} as Section;
    userModel = this.users.find(x => x.userId === id);
    const index = this.users.indexOf(userModel);
    this.users.splice(index, 1);
    this.emitValueModel.push(
        {
            title: this.user.title,
            userId: this.user.userId
        }
    );
    this.selectedUserId.emit(this.emitValueModel);
    if (this.users.length === 0) {
        this.show = false;
    }
    this.cdref.detectChanges();
}

An error message is displayed:

ERROR TypeError: Cannot delete property '1' of [object Array]

What could be causing this problem? How can I resolve it?

Answer №1

I encountered a similar issue and found information in this resource that suggested the user array contains non-configurable properties. It seems that Angular Inputs are also set as non-configurable. When you execute: this.users = this.usersInput you are essentially passing the reference of the input to this.users. The resolution is to duplicate the input array before splicing. In your scenario:

this.users = [...this.usersInput];

By the way, perform this operation within the deleteUser method rather than in afterViewInit with a local variable. There is no need for two class properties pointing to the same object.

Answer №2

Encountering a similar issue in my React application, it seems that the same problem may be present in Angular as well. The error stemmed from creating a shallow copy using the JS spread operator.

const newArr = [...oldArr];
newArr.splice(1) // All items except the first one are removed.
// This resulted in the error message: 'Cannot delete property '1' of [object Array]'

To resolve this issue, I decided to utilize lodash.clonedeep for performing a deep clone.

import cloneDeep from "lodash.clonedeep";

const newArr = cloneDeep(oldArr);
newArr.splice(1) // All items except the first one are removed.
// Problem solved!

Answer №4

Give this a shot:

removeUser(userId) {
    const index = this.allUsers.findIndex(user => user.id === userId);
    this.allUsers.splice(index, 1);
}

See it in action

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

Having trouble with JQuery click function not executing on initial click?

As I scoured through various resources looking for solutions to issues similar to mine, I stumbled upon numerous helpful insights. However, after going through approximately 15 of them, I hit a roadblock in finding someone who has encountered the exact sam ...

What is the correct way to submit a formarray in an angular application following the specified format?

When submitting a form in Angular, I'm facing an issue where only the data from the first index inside the role menu is being passed. How can I ensure that all index data is passed on submit? { "roleMenu":[{ "menu":{ "menuId": 1 }, ...

Struggling with certain aspects while learning Nodejs and ES6 technologies

Below is an example of using the ES6 method.call() method that is causing an error var obj = { name: "Hello ES6 call", greet: function(somedata) { this.somedata = somedata console.log(this.somedata) ...

Employing Modernizer.js to automatically redirect users to a compatible page if drag and drop functionality is not supported

I recently set up modernizer.js to check if a page supports drag and drop functionality. Initially, I had it set up so that one div would display if drag and drop was supported, and another div would show if it wasn't. However, I ran into issues with ...

The md-select search filter currently functions according to the ng-value, but it is important for it to also

I am using a md select search filter with multiple options available. For instance: id: 133, label:'Route1' id: 144, label:'Route2' id: 155, label:'Route3' id: 166, label:'Route4' If I input '1' ...

Differences between Pipe and Tap when working with ngxsWhen working with

While experimenting with pipe and subscribe methods, I encountered an issue. When using pipe with tap, nothing gets logged in the console. However, when I switch to using subscribe, it works perfectly. Can you help me figure out what I'm doing wrong? ...

Error encountered in Next.js: TypeScript error with code ts(7031) - The binding element 'Component' is implicitly assigned the 'any' type

Converting my NextJS project to TypeScript presented a challenge for me. When working on my _app.tsx file, I came across a type error: 'pageProps' implicitly has an 'any' type. ts(7031). The error message likely resembled this image: ht ...

What is the best way to arrange the information in JSON in ascending order and display it in a table format?

I am working with a mat-table and have used GET to display my data. I now want to sort the data in ascending order based on the db-nr from my JSON. Here is an excerpt from my JSON: { "period": 12.0, " ...

When I make a post request, I receive a response in the form of an HTTPS link, but it is not redirected to

I'm making a post request and receiving the response as follows: " [Symbol(Response internals)]: {url: 'https://login.somenewloginpage'}" My intention is to open a new page using that URL, but unfortunately it does not redirect t ...

Creating a box that is connected by lines using JSON data requires several steps. You

I am attempting to dynamically draw a line using the provided JSON data. I have heard that this can be easily achieved with flexbox. Important: I would greatly appreciate a solution involving flexbox This is what I hope to achieve: https://i.stack.imgu ...

Experiencing issues with transferring JSON response from Axios to a data object causing errors

When I try to assign a JSON response to an empty data object to display search results, I encounter a typeerror: arr.slice is not a function error. However, if I directly add the JSON to the "schools" data object, the error does not occur. It seems like th ...

I could really use some assistance with the concept of "AJAX" - can anyone help

After spending several months working with AJAX, I have come to understand the typical request lifecycle: Sending parameters to a background page (PHP/ASP/HTML/TXT/XML ... what other options are available?) Performing server-side processing Receiv ...

Encountered an issue when attempting to send data using this.http.post in Angular from the client's perspective

Attempting to transfer data to a MySQL database using Angular on the client-side and Express JS on the server-side. The post function on the server side works when tested with Postman. Here is the code snippet: app.use(bodyParser.json()); app.use(bodyPa ...

Grouping items by a key in Vue and creating a chart to visualize similarities among those keys

I am working with an object that has the following structure; { SensorA: [ { id: 122, valueA: 345, "x-axis": 123344 }, { id: 123, valueA: 125, "x-axis": 123344 }, { id: 123, valueA: 185, "x-axis": 123344 }, { ...

When sending multiple JSON objects in an HTTP POST request to an ASP.NET MVC controller action, they may not be properly bound

I am passing two JSON objects to an ASP.NET MVC controller action, but both parameters are showing as null. Can anyone identify the error, possibly related to incorrect naming? /* Source Unit */ var sourceParent = sourceNode.getParent(); var sourceUnitPa ...

The outcome of AES encryption varies when comparing Node JS with C# programming languages

In a particular scenario, I need to encrypt and transmit text using the AES 256 algorithm. The decryption process will be handled by client-side C# code. Here is the encryption code in JavaScript: const crypto = require('crypto'); algorithm = ...

Identifying Changes with jQuery Event Listeners

I am trying to run some javascript code that is in the "onchange" attribute of an HTML element. For example: <input id="el" type="text" onchange="alert('test');" value="" /> Instead of using the onchange attribute, I want to trigger the e ...

Using iframes in Angular 2/4's index.html

I'm currently working on an angular application and for session management, I've implemented OpenID Connect Session Management. I am attempting to inject iframes into the application. I need to include an iframe in my index.html as follows: < ...

What is the process of converting a union type into a union of arrays in TypeScript?

I have a Foo type that consists of multiple types For example: type Foo = string | number I need to receive this type and convert it into an array of the individual types within the union type TransformedFoo = ToUnionOfArray<Foo> // => string[] ...

Arranging input elements horizontally

this issue is connected to this post: Flex align baseline content to input with label I am grappling with the layout of my components, specifically trying to get all inputs and buttons aligned in a row with labels above the inputs and hints below. The CSS ...