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

The Element Datepicker incorrectly displays "yesterday" as an active option instead of disabled when the timezone is set to +14

After adjusting my timezone to +14 using a chrome plugin, I noticed that the calendar app is displaying incorrect disabled dates. You can view the issue here. This is the formula I'm currently utilizing to disable dates: disabledDate(time) { re ...

Error: The function res.json is not recognized. Despite searching through related inquiries, I cannot find a solution to my specific issue

Struggling to find a solution and avoiding repetitive questions, I am facing an issue with my bug tracker. After submitting the form and sending it to the server side, the bug is created in the database. However, when I save the bug using await bug.save() ...

Enhancing a React Native application with Context Provider

I've been following a tutorial on handling authentication in a React Native app using React's Context. The tutorial includes a simple guide and provides full working source code. The tutorial uses stateful components for views and handles routin ...

Testing Angular 7 Services with RxJs6: Verifying Error Handling with throwError

I am interested in testing the throwError functionality. When I test with a wrong id of 0 using getById, my expectation is that throwError should return an error. This is my service: getById(fooId): Observable<Foo> { return this.getAll().pipe(mer ...

Node.js server containerized with Docker: deleted express route remains accessible

I recently developed a Twitch Chat Bot using Dockerized (docker compose), Node.js v16 with express. To create an authorize-page for users to authorize my bot on the Twitch API, I utilized the route /auth/request: this.serverUrl = serverUrl; this.port = po ...

The CORS Policy has prevented Angular from accessing the header, as the request header field for authentication is restricted

After reviewing a multitude of similar questions regarding CORS and headers, I have attempted various solutions but I am still encountering this error specifically in Google Chrome. Access to XMLHttpRequest at 'https://service.domain.com/clientlist&ap ...

"Despite the successful execution of the PHP script, the error function in the Ajax POST request

I am working on developing a mobile app using jQuery, jQuery Mobile, and HTML with PhoneGap. I have successfully implemented AJAX to call PHP scripts on the server for tasks like updating, inserting data, and sending emails. However, I consistently encoun ...

Problem with translating a variable into a selector in JQuery

When attempting to make my Jquery code more flexible, I decided to extract the selector and access it through a variable. However, despite creating variables for both selectors, neither of them seem to be functioning properly. I am confident that the issue ...

Exploring ways to access data stored in interconnected models, such as MongoDB and NodeJS

As a newcomer to querying, I attempted a unique exercise to practice but unfortunately did not achieve the desired outcome. I have three models: const userSchema = new Schema({ info1: String, info2: String }, const serviceSchema = new Schema( { name ...

Examining the dimensions of a div element in AngularJS

As I delve deeper into understanding AngularJS and tackling the intricacies of how $watch operates, a specific scenario has caught my attention. I want to monitor and track changes in the dimensions of the div element with an ID of "area". My intention is ...

Utilize angularjs daterangepicker to refine and sift through data

I am currently utilizing the ng-bs-daterangepicker plugin by ng-bs-daterangepicker and encountering difficulty in filtering when selecting a start date and end date. Below is a snippet of my code: <input type="daterange" ng-model="dates" ranges="range ...

What causes the ngIf directive to update the view of an HTTP observable only upon reloading the page?

Presently, I am utilizing a template: <div *ngIf="(currentUser | async)?.can('book')">Book Now</div> accompanied by its component: readonly currentUser: Observable<CurrentUser>; constructor(private userService: UserSe ...

An issue has occurred: Failure to execute spawnSync PATH/target/node/node ENOENTNGCC. Please refer to the

Attempting to initiate my angular project using ./mvnw is resulting in an error when the build runs ng build --configuration development. The error message thrown reads as follows: Generating browser application bundles (phase: setup)... [INFO] /home/use ...

Troubleshooting: Issue with Displaying $Http JSON Response in AngularJS View

Struggling to retrieve JSON data from an API and display it in a view using AngularJS. Although I am able to fetch the data correctly, I am facing difficulties in showing it in the view. Whenever I try to access the object's data, I constantly receive ...

The function is unable to accurately retrieve the state value

In my app, I have a component where I'm attempting to incorporate infinite scroll functionality based on a tutorial found here. export const MainJobs = () => { const [items, setItems] = useState([]); const [ind, setInd] = useState(1); const ...

The 'eventKey' argument does not match the 'string' parameter. This is because 'null' cannot be assigned to type 'string'

Encountering an issue while invoking a TypeScript function within a React Project. const handleLanguageChange = React.useCallback((eventKey: eventKey) => { setLanguage(eventKey); if(eventKey == "DE") setCurre ...

Error in Angular2: Method this.http.post is invalid and cannot be executed

import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/catch'; // import 'rx ...

Creating a quiz with just one question in React: A step-by-step guide

How can I add the functionality to handle correct and incorrect answers? I've designed a single-question quiz with multiple options. The Quiz component has been created. See the code snippet below: Quiz Component export default function Quiz(props) { ...

Using Typescript to import a module and export a sub function

I am currently using mocha for testing a function, but I have encountered an error while running the test file. The structure of my files is organized as follows: server |-test | |-customer.test.ts |-customer.js Here is the content of the customer.js fi ...

What is the best way to store all rows in a dynamically changing table with AngularJS?

I am facing an issue while trying to dynamically add rows for a variable that is a String array in my database. The problem is that it only saves the last value entered in the row instead of saving all of them in an array. Here is my current view code: &l ...