Reversing ngModel modifications does not accurately display changes in the view

Presently, my table contains editable cells, with the functionality to undo changes to each cell. To achieve this, I initially created a duplicate of each object in the array.

Upon initialization, I mapped the array to create a new array with old values stored in a separate property:
this.previousArr = this.mainArr.map(item => {
  item.oldValues = Object.assign({}, item);
  return item;
})

When the cancel action is triggered, I restore the cell's old values instead of the new ones:

cancel(action) {  
   action = Object.assign({}, action.oldValues);
}

However, after testing out this implementation in stackblitz, I noticed that while the values revert back to the old ones in the console, they don't reflect in the actual view. Can you help identify the issue here?

Answer №1

The reason for this occurrence is due to the item you provide to the cancel function possessing a distinct reference from the one in your temp.

One approach that may resolve this issue is as follows:

  cancel(item) {
    const {name, city} = item.oldValues; 
    this.mapedArr[this.mapedArr.indexOf(item)] = {...this.mapedArr[this.mapedArr.indexOf(item)], name, city} 
  }

Feel free to check out the updated version on your Stackblitz

Answer №3

Avoid the use of object.assign in this scenario as the name is being placed in another property called oldValue.

  constructor() {
    this.mapedArr = this.arr.map(i => {
      i.oldValues = i.name
      return i;
    })
    console.log('this.mapedArr ', this.mapedArr);
  }

  cancel(i) {
    console.log('i new', i);
    i.name =  i.oldValues 
    console.log('i old', i);
  }

See the Demo

Answer №4

your component:

  constructor() {
     this.copyOfArr = JSON.parse(JSON.stringify(this.arr));
     console.log('this.copyOfArr ', this.copyOfArr);
  }

 undoChanges(i) {
     this.copyOfArr[i] = JSON.parse(JSON.stringify(this.arr[i]));
 }

your html:

<p *ngFor="let i of copyOfArr; let ind = index">
   Name: {{i.name }}<br>
   City: {{ i.city }}<br>
   <input type="text" [(ngModel)]='i.name' /><br>
   <button (click)='undoChanges(ind)'>Undo Changes</button>
<br>
<br>
</p>

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

Oops! Looks like there's an issue with the type error: value.forEach is

I am working on creating an update form in Angular 6 using FormArray. Below is the code snippet I have in editfrom.TS : // Initialising FormArray valueIngrident = new FormArray([]); constructor(private brandService: BrandService, private PValueInfoSe ...

Guide on integrating react-tether with react-dom createPortal for custom styling of tethered components based on their target components

Within a Component, I am rendering buttons each with its own tooltip. The challenge is to make the tooltip appear upon hovering over the button since the tooltip may contain more than just text and cannot be solely created with CSS. The solution involves ...

Clear out the existing elements in the array and replace them with fresh values

Within my Progressive Web App, I am utilizing HTTP requests to populate flip cards with responses. The content of the requests relies on the selected values. An issue arises when I choose an item from the dropdown menu. It triggers a request and displays ...

Type of object is unidentified in Vuejs with Typescript error code ts(2571)

Currently, I am facing a challenge with storing JSON data in a variable within my Vue project. Below is the code snippet used to upload and store the file: <input type="file" id="file" ref="fileSelect" class="custom- ...

The ability of Angular 4 ngComponentOutlet to load dynamic components is great, however, there seems to be an issue

Currently, I am faced with the challenge of loading various 'parent' components and injecting route content into these individual parent components by utilizing ng-content in each one. Essentially, the purpose of each parent component is to manag ...

Steps for adding Node modules to a Nexus private repository

Running my organization's private Nexus npm repo, all packages are installed on my local machine through the internet. I want to store all packages on my Nexus private repo and have successfully uploaded them using the npm publish command. However, wh ...

Unregistered outlet name unrecognized

I am currently working on developing a tabs component within one of my components, utilizing named outlets for this purpose. At the moment, I have my default outlet set up to display each page, and I would like to incorporate a named outlet within one of ...

Jasmine: utilizing unit test to spy on the invocation of a nested function

When running unit tests for an Angular app, I need to spy on a function called func1 to check if it is being called. However, within func1 there is a call to func2 and I also want to spy on that to see if it is being called. How should I structure my unit ...

Having trouble installing Angular 2 with npm?

Encountered an error while trying to install Angular 2: npm ERR! Windows_NT 6.1.7601 npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\ic020019\\AppData\\Roaming\&bs ...

Generating ambient module declarations in Typescript for distribution on NPM

Seeking advice on generating TypeScript ambient module declarations for a node (commonjs) npm package being developed in TypeScript. Encountering confusion around the proper method to have TypeScript create these ambient module declarations for node / comm ...

Ensuring the Current Page is Valid Before Progressing to the Next Step in Angular-Archwizard

Currently, I am working with Angular-7 and using angular-archwizard to create a multi-step form. The issue I am facing is that the form allows users to proceed to the next step without filling in all the required fields. My goal is to restrict users from m ...

Obtain the file path relative to the project directory from a Typescript module that has been compiled to JavaScript

My directory structure is as follows: - project |- build |- src |- index.ts |- file.txt The typescript code is compiled to the build directory and executed from there. I am seeking a dependable method to access file.txt from the compiled module without ...

Passing data from child to parent in Angular using EventEmitter

I have integrated a child grid component into my Angular application's parent component, and I am facing an issue with emitting data from the child to the parent. Despite using event emitter to transmit the value to the parent, the variable containing ...

Protractor experiencing difficulty recognizing Angular functionality

Recently, I made the switch to using Protractor for running end-to-end tests on my Angular application. However, the e2e tests have suddenly started failing because Protractor is unable to detect Angular on the website. I raised this issue in their GitHub ...

Having trouble utilizing datepipe with locale format

Currently, I'm constructing a website using angular2 final alongside webpack cli. One of my specific requirements is to showcase the date in the nl-NL locale. The html code snippet that I have written for this purpose looks like: {{eventDate | date:& ...

Restricted inclusive collection utilizing embedded identifier

Attempting to segregate a discriminated union array into separate arrays of its union types has presented some challenges. I came across this particular question that provides generic discriminators. Unfortunately, the dataset I am working with doesn&apos ...

How to display placeholder text on multiple lines in Angular Material's mat form field

Within a standard mat-form-field, I have a textarea enclosed. However, the placeholder text for this Textarea is quite lengthy, leading to truncation with an ellipsis on mobile devices due to limited space. My goal is to adjust the placeholder text based ...

Expanding material UI theme choices through module augmentation is currently ineffective with TypeText

For those experiencing the issue, a codesandbox has been provided for convenience. Click here to access the codesandbox. Curiously, the TypeText feature is not functioning properly while the SimplePaletteColorOptions is working as expected. Despite being ...

Encountering a node-sass problem during npm installation in my Angular project on Mac OS

While attempting to install node_modules for my Angular project on Mac OS, I encountered an issue with node-sass. My Node.js version is v16.13.2 and the node-sass version in the project is ^4.14.1. The package.json files can be viewed in image1 and image2. ...

Error occurring with the gulp task runner

Encountering an error while using the task runner for my "gulp" file. My project involves Angular 2 and Asp.net Core. The "typings" folder is set up with a "typings.json" file that contains the following: { "resolution": "main", "tree": { "src": ...