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

Ensuring that the field remains active in Angular2 even after editing it with a value

When the 3rd dropdown value is selected in the first field dropdown, it enables the 2nd field. However, when I edit and change a different value, since the 2nd field is disabled, I receive null or undefined as the value. I want the 2nd field to retain its ...

The attribute 'randomUUID' is not found within the 'Crypto' interface

I attempted to utilize the crypto.randomUUID function in my Angular app version 13.1, however, it does not seem to be accessible. When trying to use it, I encountered this error: TS2339: Property 'randomUUID' does not exist on type 'Crypto ...

What purpose does the pipe method serve in RxJS?

It seems like I understand the basic concept, but there are a few unclear aspects. Here is my typical usage pattern with an Observable: observable.subscribe(x => { }) If I need to filter data, I can achieve this by: import { first, last, map, reduce, ...

Uploading data through AJAX without saving it in the database

Can someone please assist me? I am encountering an issue where I am uploading multiple data using an AJAX request. The data appears to upload successfully as I receive a response of 200 OK, but for some reason, the data is not being stored in the database. ...

Customize the columns of your Angular Material 2 table by defining them using TemplateRef and ngTemplateOutlet

Looking to create a flexible material table with the ability to utilize TemplateRef along with ngTemplateOutlet for generating columns. Check out this demo where I have employed the cards component within my custom material-table component. Inside the card ...

What is the best way to import multiple classes from a module folder in Angular2 using TypeScript?

In my Angular2 application, I have organized my modules as follows: /app /content /models resource.ts container.ts entity-type.ts index.ts /services /whatever ...

Animate the parent container of ng-view in Angular by targeting an element within ng-view

Are you able to use CSS animations to animate a div's background color that is located outside of the ng-view, while using a directive on a $state within the ng-view? The ng-view already has CSS animations for routing. When I try to add animation cl ...

Error: The plugin "videoJsResolutionSwitcher" could not be located on AngularCli platform

Unable to recognize VideoJs-Resolution-Switcher as a Plugin! Issues: - Angular2 - Unable to find plugin: videoJsResolutionSwitcher - player.updateSrc is not a function Library Information: - videojs: https://github.com/videojs/video.js/ - vi ...

The function RegisterOnChange is not a valid function

I utilized FormBuilder(fb) to create this form. this.serviceRecordForm = this.fb.group({ client: [], serviceRecordItem: this.fb.group({ productStatus: [''], password: [''], hasBackup: ...

Django and VueJS: Error 403 - Forbidden request due to missing or incorrect CSRF token

My tech stack includes Django and Django REST framework on the backend, along with Vue.js on the frontend. While GET requests function smoothly and POST requests using Postman or Insomnia work fine, encountering an error in the Browser console when sending ...

It appears that the crackling noise is being generated by AudioContext.decodeAudioData

I am currently in the process of developing an electron app that enables users to cut and rearrange multiple audio samples while seamlessly playing them back. The combined duration of these samples can exceed an hour, making it impossible to decode and sto ...

Implementing the row delete function in MUI DataGrid using JavaScript

My grid has a delete icon button in each row, but it's not deleting the row. Can someone please help me with this issue? I'm working on a todo app where each row should have its own delete button. I'm struggling to connect the deleteTodo co ...

Add owl carousel to your npm project in any way you see fit

After struggling for a while, I finally wanted to implement owl-carousel, but couldn't figure out how to connect it using npm and webpack. The official NPM website states: Add jQuery via the "webpack.ProvidePlugin" to your webpack configuration: ...

An error is anticipated when () is added, but surprisingly, I still encounter an error as well. This issue arises in React-Native and Typescript

I am still relatively new to React-Native, but I have been using React-Native, TypeScript, and integrating it with Firebase. An unusual error has occurred, which is visible in the screenshot below. However, when checking in VSC, the error seems to be non-e ...

Initiate a POST request to download the file upon clicking the button

How can I initiate a file download when a button is clicked? During testing, I noticed that sending a GET request using <Link href="/api/generate-pdf"> works perfectly and the PDF file gets saved. However, when I use a button to hit the API, the dow ...

Could someone assist me in understanding why VScode is displaying an error stating it cannot locate a module?

node:internal/modules/cjs/loader:1051 throw err; ^ Error: The module '/Users/ben/Desktop/GA/unit2/week5/GA_Project_2/QuotaQuest/index.js' cannot be found. at Module._resolveFilename (node:internal/modules/cjs/loader:1048:15) at Modul ...

Tips for automatically resizing a canvas to fit the content within a scrollable container?

I have integrated PDF JS into my Vue3 project to overlay a <canvas id="draw_canvas"> on the rendered pdf document. This allows me to draw rectangles programmatically over the pdf, serving as markers for specific areas. The rendering proces ...

What is the method for displaying html files in a POST request?

This is the code snippet I am working with: app.post('/convert', function(req,res){ var auxiliar = "somo Ubuntu command line(this works)"; exec(auxiliar, function(err, stdout, stderr){ if(err){ console.log ...

The paths specified in Node.js and Express are having difficulty finding the resource files for CSS and JavaScript

I am currently using Express to develop a basic website. Everything was running smoothly until I attempted to add the following code to handle 404 errors: app.get('/*', function(req, res) { res.render('404.ejs',{ title: ' ...

Unable to properly test the functionality of the material-ui select component due to an error being thrown stating that the function is not being called

I've been utilizing the material-ui select component in my project and am currently writing tests for it. However, I've encountered an issue regarding testing the onChange event of the component. Here's a snippet of the code for my component ...