When using Angular 2, the array.splice() function is causing the elements to be removed from the

I am currently working with an HTML table that has default checked rows.

<table>
    <tr>
        <th></th>
        <th>Id</th>
        <th>Name</th>
        <th>Initial</th>
    </tr>
    <tr *ngFor="let name of names; let i = index">
        <td><input type="checkbox" [checked]="chk" (change)="onTaChange(name, $event.target.checked,i)"></td>
        <td>{{name.id}}</td>
        <td>{{name.Fname}}</td>
        <td>{{name.Initial}}</td>
    </tr>
</table>

I have created another array to store unchecked/checked objects. In the onTaChange() method, I pass the index in splice() to remove the object at that index (unchecked row in the table). However, the rows(objects) are getting removed even if they belong to different arrays of objects.

My goal is to have a second array containing only the checked/unchecked rows of objects. Can anyone provide assistance with this?

Plunker

Answer №1

Explanation: Arrays store references, which means that when you create the following:

alteredNames:string[]=this.names;

alteredNames is not a brand new array but rather a reference to the original array, so any changes made in either array will be reflected in both.

Resolution: To avoid this issue, make a deep copy of the array by using _.cloneDeep(this.name).

Answer №2

When it comes to copying an array, there are various modern methods available:

  • loop
  • Array.from
  • Array.slice
  • Array.concat
  • JSON.parse(JSON.stringify(arr))
  • [...arr] from ES6

However, most of these methods do not create a new instance for the new array, with the exception of loop or Array.concat(). Therefore, in your situation, you will need to use either the loop method using Array.forEach and Array.push, or the Array.concat() method to copy the array.

Here is a helpful plunker for reference. I hope this information proves useful.

Answer №3

When utilizing the same reference and passing the entire array to your OnTaChange method

The slice() method can be used to make a clone of the array object

this.alteredNames=this.names.slice(0);

Additionally, as Pankaj mentioned,

this.alteredNames=Object.assign([], this.names)

In addition to the above methods, a fantastic 3rd party library can also achieve similar results,

export class App {
  chk:boolean = true;
  names:string[] = [
    {
      "Fname": "Bunty",
      "id": "1",
      "Initial":"G"
    },
    {
      "Fname": "Ronny",
      "id": "2",
      "Initial":"K"
    },
    {
      "Fname": "Sam",
      "id": "3",
      "Initial":"P"
    },
    {
      "Fname": "James",
      "id": "4",
      "Initial":"M"
    }
    ];
    alteredNames:string[];
  constructor() {
   this.alteredNames=_.clone(this.names) //////////this works
   // or
   this.alteredNames=_.cloneDeep(this.names) // will also work. 
  }

  onTaChange(name:string, $event.target.checked:boolean,i:number){
    if(!checked){
      this.alteredNames.splice(i,1); 
      console.log(this.alteredNames);
    }
    else{
      this.alteredNames.push(name);
    }
  }
}

@NgModule({
  imports: [ BrowserModule, FormsModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

Lodash should be included from this CDN as shown below

Updated Plunker

Furthermore,

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

Instructions on transferring an image to a server. The image is located on the client side within an <img> tag

Looking for an effective way to upload an image when the type is “file”? The goal here is to send an image from an image tag to the server without converting it into base64 due to size constraints. <form id="form-url"> <image src ...

How to target and set focus on dynamically generated input field when the ID is unknown

I am facing an issue with a jQuery/AJAX function that loads HTML form elements from the server. The form fields vary, and I want to set focus on the first available input field after the load is complete. I have tried: $(':input:enabled:visible:firs ...

Can the garbage collector in Typescript/JavaScript effectively handle circular references, or does it result in memory leaks?

When working in languages such as C#, managing memory is not a problem. However, this can lead to difficult-to-find memory bugs in other languages. Is it safe to use the following code snippet in Typescript or Javascript without encountering any issues? c ...

Utilizing AngularJS with dual controllers within a single view

I recently started working on an angularJS web app using a purchased template that has all its controllers, routes, and directives in a single file called app.js. This is my first dive into angularJS and front-end development. Hoping to become a Full Stac ...

Using JavaScript, you can manipulate the position of a line on a canvas to

I want to create a feature where users can manipulate lines on a canvas by skewing them. This means they would be able to drag one end point of the line to a desired point on the same x-axis using JavaScript and HTML5 canvas. Can someone please provide g ...

Creating dynamic grids in React.js by utilizing HTML

Currently, I am tackling one of the projects on FCC which is the Game of Life. Prior to diving in, my focus is on figuring out how to render a grid on the page. I aim to modify the table dimensions while ensuring it fits neatly within its container. The ...

Troubleshooting an Angular.js "Hello World" application that is malfunctioning

I've been trying to get a simple Hello World app working by following different tutorials, but it doesn't seem to be functioning correctly. I've double-checked my code and everything looks right to me. Could someone please assist me in troub ...

I can't quite understand the reasoning behind why this specific function is designed to output

I've been working on a JavaScript exercise and struggling to understand the logic behind it. The exercise involves a function named "mystery" that utilizes several basic functions to return an array in reversed order. Despite spending hours trying to ...

Adding a modified (id) content inline template element to another element: A step-by-step guide

In the given scenario, I am looking to achieve a function where each time the add button is clicked, the content within the template div should be appended to the element with the landingzone class. Additionally, it is important that the NEWID changes for ...

analyzing strings by comparing their characters to another string

In a scenario where I have two strings; let's call them string a="a-b-c" and string b="a-b". I am looking to determine whether every letter in string b is present within string a. ...

Uploading files in Angular alongside other data within the same HTTP post request

Can a file be added along with other information in a single post? export class ProfileExtraData { public id: number; public fullName: string; public file: any } return this.httpClient.post<void>(`${this.apiBaseUrl}/save`, profileExtraD ...

Having trouble with Three JS shadows not displaying correctly?

I recently built an interactive 3D model on my website using ThreeJS, but I'm facing an issue with getting the shadows to work properly. As a beginner in ThreeJS, I might be missing out on some crucial steps. Below is the JavaScript code I've us ...

Angular directive has issues with $compile functionality

This Angular directive automatically appends a new HTML item to the page every time my model changes: app.directive('helloWorld', function($compile) { return { restrict: 'AE', replace: true, scope:{ ...

Using the Coinbase.com API with HMAC authentication in a Node.js environment

I recently delved into some node.js documentation, specifically crypto and https, in an attempt to utilize the coinbase.com API within my coin.js file to retrieve the bitcoin balance of my account. However, I am encountering errors. Upon running the code w ...

Expanding external type declarations within Typescript

I am currently working with Typescript and the ant design library. My goal is to extend an existing interface by adding a single property. To start, I imported the original interface so you can see the folder structure: import { CollapseProps } from &apo ...

Looking to extract, interpret, and display PDF documents using React?

I'm working on displaying a PDF file from an external URL. My goal is to extract text from the PDF for analysis, and then present a specific section of a page to users in my React application. This will involve cropping the content using coordinates o ...

Guide on replacing placeholders in a text with input fields and connecting them with v-model in Vue.js

I am currently working on creating an exam page that features fill in the gap type questions. These questions have placeholders where students need to insert the correct words or phrases. The questions are fetched via an ajax request and consist of simple ...

Nextjs Clerk: The <SignIn/> element lacks proper configuration

I attempted to resolve the issues indicated in the error message below, but unfortunately, I was unsuccessful. How can I troubleshoot this error and perform an “auth-callback with clerk”? - The technologies used include Nextjs, Nextjs Actions, Clerk, a ...

Encountered an unexpected error while attempting to integrate my custom npm library "MyModule" into my Angular 2 project

I have created my own library which consists of one module and one component. After compiling my library, I add it to my main project using the following command: npm link ng-shared Next, when I attempt to import SharedModule in my module file as shown b ...

Tips for effectively managing loading state within redux toolkit crud operations

Seeking guidance on efficiently managing the loading state in redux-toolkit. Within my slice, I have functionalities to create a post, delete a post, and fetch all posts. It appears that each operation requires handling a loading state. For instance, disp ...