Angular 2 TypeScript: The concat() function operates as mutable within the framework

When I declare an array on an @Injectable provider, my intention is to use it across different components.

  normeList: any[] = [
    {
      name: 'choice 1',
      type:'false'
    },
    {
      name: 'choice 2',
      type:'false'
    }
  ];

In a component, I assigned the array in this way:

this.myArray = [].concat(this.sharedListDeclarationProvider.normeList);

As I work with myArray in the view, I modify the type value from false to true;

The issue arises when the changes made to 'myArray' affect both the component itself and the original normList in the provider service.

I am seeking guidance on how to update the values of myArray without impacting the contents of normeList in the provider.

Answer №1

Are you looking to duplicate the normeList array from the provider and utilize it within your component?

If you wish to replicate the array without causing any changes or side effects, you can utilize the slice method of the array for simple arrays. However, for complex arrays, you have a few options:

  • JSON.parse(JSON.stringify(array))
  • The ES6 version using the spread operator [...array] along with map
  • A combination of map with Object.assign

For your situation, you can replace the following line:

this.myArray = [].concat(this.sharedListDeclarationProvider.normeList); 

with the following:

this.myArray = this.sharedListDeclarationProvider.normeList.map(item=>Object.assign({}, item));

or even shorter using the ES6 spread operator:

this.myArray = this.sharedListDeclarationProvider.normeList.map(item=>{...item));

Answer №2

One way to manipulate data in JavaScript is by using the functions JSON.parse and JSON.stringify.

By applying JSON.parse and JSON.stringify, you can effectively clone an array like this: this.myArray = JSON.parse(JSON.stringify(this.sharedListDeclarationProvider.normeList));

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

Passing data to a server-side component in Next.js: a guide

I am working on a website dedicated to dynamic blogs and I need to pass parameters to an API URL in order to retrieve a specific blog. However, I must ensure that the approach I take does not hinder SEO by utilizing local storage, cookies, or any other c ...

Issues with the daterange filter in Angular SlickGrid causing functionality problems

Within Angular SlickGrid, I have implemented two date columns where the values are derived from a specific class. These columns correspond to two date fields within this class. My intention is to represent these values in dateTimeShortIso format and apply ...

Instructions on accessing the subsequent li a starting from a designated location

My goal is to change the link color of the button with the id #idIMMUNOLOGY_9, which has the class .active_default, but I must start from the element with the id #idTERRITORIAL_8. I attempted this approach : $('#idTERRITORIAL_8').parent().find( ...

Sending form data from a third-party website to Django

Currently, I am running a Django website that holds user information. My goal is to host forms on external websites, such as a newsletter signup form. I want to be able to extract data from a queryset in the URL and send it back to my Django site. At the m ...

The radio button that disables other inputs only functions correctly for a single element when using Query Selector, but does not work with Query

I have attempted to develop a form section that is disabled when the user selects option A and enabled when they choose option B. document.getElementById('delivery').onclick = function() { var disabled = document.querySelectorAll(".dis ...

What steps should I take to troubleshoot this Angular issue within a Visual Studio 2022 project that utilizes the Standalone Angular template?

After going through this tutorial and meticulously following each step, I encountered an error when trying to run the application: https://i.sstatic.net/EvYgg.jpg Can anyone advise on how to resolve this issue? I'm facing a similar error while attem ...

Is there a way to generate bootstrap divs by parsing csv text?

As I am working on a Bootstrap 3 image gallery, I have noticed that there are multiple recurring divs with a similar structure as shown below: <figure class="col-1 picture-item" data-groups='["groupA"]' data-date-created="2018" data-title=" ...

Switching a div class in Angular 6 with a button click: A step-by-step guide

In this scenario, I have a div with the class name old. There is also a button that, when clicked, should toggle the div's class name between old and new. I am looking for a solution using Angular 6. Below is the code snippet: I am relatively new to ...

The overlappingmarkerspidifier is throwing an error because it is unable to access the property '__e3_' of an undefined variable

I am attempting to implement the overlapping marker spidifier feature in my code. I followed the instructions provided in this link: functioning code of oms However, upon creating the OverlappingMarkerSpiderfier object, I encounter the error: Uncaught Typ ...

Simplified Method for Verifying Null and Undefined in Typescript

Hey there, I'm currently working on an Angular 11 project and I'm facing a challenge when it comes to checking for null and undefined values. In my scenario, I have three strings - equipmentId, roomId, and personnelId, as well as a boolean flag ...

Migration of old AngularJS to TypeScript in require.js does not recognize import statements

I am looking to transition my aging AngularJS application from JavaScript to TypeScript. To load the necessary components, I am currently utilizing require.js. In order to maintain compatibility with scripts that do not use require.js, I have opted for usi ...

Highlight or unhighlight text using Javascript

Currently, I am facing a challenge in highlighting specific words on an HTML page. Although I have succeeded in highlighting the desired element, I am struggling with unhighlighting the previous word when a new search is conducted. Despite my attempts to i ...

The component 'ProtectRoute' cannot be utilized within JSX

While using typescript with nextjs, I encountered an issue as illustrated in the image. When I try to use a component as a JSX element, typescript displays the message: ProtectRoute' cannot be used as a JSX component. import { PropsWithChildren } from ...

npm encountered a premature closure

I recently purchased and started using a ReactJS template which you can check out here My goal is to install all the dependencies by running npm install in the root directory of the template (React-App) However, I encountered an ERROR message like this: ...

Can I find a better approach to optimize this code?

How can I refactor this code to move the entire DB query logic into a separate file and only call the function in this current file? passport.use( new GoogleStrategy({ clientID: googleId, clientSecret: clientSecret, callbackURL: ...

Using TypeScript to Extract Keys from an Array

Is it possible to mandate the keys of an interface to come from an array of strings: For instance, consider the following array: const myArray = ['key1', 'key2']; I aim to define a new interface named MyInterface that would require al ...

Tips for transferring variables as arguments in javascript

Currently, I am immersed in a test project aimed at expanding my knowledge of web development. Unexpectedly, I have encountered an issue that has left me puzzled on how to proceed. Within this project, there exists a table consisting of 11 cells. While 9 ...

Executing JavaScript - Triggering an 'onClick' event within a For loop to dynamically load multiple hyperlinks

I am currently working on creating a listview using JSON data. However, when I call an 'onclick' function from a For loop, the link opens in a new window and loads three URLs into the browser's URL input. Is there a way to modify the code be ...

Steps to Extract the key value from the parseJson() function

Could someone assist me in retrieving the value of the "id_user" key from the script provided below? JSON.parse({ "data": [ { "id_user": "351023", "name": "", "age": "29", "link": "http://domain. ...

How to dynamically apply component-specific CSS in NextJS based on conditions

I'm working on my nextjs project and encountered an issue with adding conditional styling to a component. To address this, I created a component-level stylesheet called MyComponent.module.css, which includes the following styles: .primary { color: ...