Guide to Reverting the Two-Way ngModel Binding Data in Angular 2

I am utilizing a form in angular 2 that includes two-way binding data value ([(ngModel)]) to enable both edit and add functionality.

When a user selects the edit option on the listing page and modifies the input, the new values automatically appear on the list page. Rather than saving, the user can click the cancel button to revert back to the old value which should be displayed on the listing page.

project-form.component.html
---------------------------
   <input class="form-control"  type="text" size="30" pInputText [(ngModel)]="project.title" name="title" pTooltip="Enter your username"/>

    <ul class="list-group">
          <li *ngFor="let event of project" class="list-group-item">
            <span class="event_release">{{event.startDate | date: 'dd/MM/yyyy'}} </span><br />
            <strong>{{event.title}}</strong>
          </li>
        </ul>

Project-form.component.ts 
-------------------------
@Input() project: Project;

Upon submission, the variable (this.project) is updated with the modified values thanks to two-way binding. However, if the user clicks the cancel button, the changes need to be rolled back to the original values stored in this.project.

Answer №1

To solve the issue you're experiencing, you need to create a deep copy of the 'project' object. The problem arises because both the list page and edit page are using the same instance of the object. Any changes made to the object in one place will reflect in the other as well.

Here's the JavaScript code to use (do this in the edit page):

let project_copy =JSON.parse(JSON.stringify(project))

In the edit page, make sure to work with the 'project_copy' variable instead of the original 'project' variable.

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 TypeScript error states that the argument type 'string | undefined' cannot be assigned to the parameter type 'string'

Receiving TS error that says "Object is undefined" I am attempting to retrieve the "userid" from my headers. However, I keep encountering the error message "Argument of type 'string | undefined' is not assignable to parameter of type 'str ...

The continuous re-rendering is being triggered by the Async/Await Function

I am facing an issue with fetching data from the backend using axios. The function is returning a Promise and each time I call it, my component keeps rendering continuously. Below is the code snippet: import { useState } from "react"; import Ax ...

New Requirement for Angular Service: Subclass Constructor Must Be Provided or Unable to Resolve all Parameters for ClassName (?)

During a recent project, I encountered an issue while working on several services that all extend a base Service class. The base class requires a constructor parameter of HttpClient. When setting up the subclass with autocomplete, I noticed that their con ...

Angular site deployed to Firebase Hosting encounters a connection issue with ERR_CONNECTION_REFUSED - could this be due to a

I recently tested an admin template from angular-templates.io and everything was working perfectly fine in the production build. I then uploaded it to Firebase Hosting specifying dist/browser (which was created during the production build). However, upon l ...

Exploring limitless possibilities with Vue slot manipulation

Imagine I am looking to develop a multi-layered Component for reusability, similar to a 'Tab' UI. This would allow developers to use it like this: <tabs> <tab label="My First Tab"> Content for first tab which could co ...

Using react-google-charts to create visually appealing dual-Y stacked bar charts

I am currently working on developing a bar chart with specific criteria in mind. My data follows the format: [month, region, totalSalesForCompanyA, totalSalesForCompanyB] I have successfully implemented the following charts: A dual-Y bar chart where mo ...

Tips for displaying only the components associated with the user's role in Angular

Greetings everyone! I have a dashboard that features a menu showcasing all the components. I am looking to implement a functionality where, if logged in with the admin role, all components should be displayed. On the other hand, if logged in with the respo ...

Zone.js error: Promise rejection caught

When I call a function from an external library on page load in my Angular application, Chrome dev tools console shows the error message: "Unhandled Promise rejection: Cannot read properties of undefined (reading 'page') ' Zone: <root> ...

What is the best way to display the complete text or wrap a menu item in an Angular Material menu?

Is it possible to display the full text of a menu item instead of automatically converting it to ellipses or breaking the word? I've tried various CSS methods without success. Any suggestions? https://i.stack.imgur.com/3l7gE.png #html code <mat-m ...

How to focus on an input element in Angular 2/4

Is there a way to focus on an input element using the (click) event? I'm attempting to achieve this with the following code, but it seems like there may be something missing. (I am new to Angular) sTbState: string = 'invisible'; private ele ...

Issue with type narrowing and `Extract` helper unexpectedly causing type error in a generic type interaction

I can't seem to figure out the issue at hand. There is a straightforward tagged union in my code: type MyUnion = | { tag: "Foo"; field: string; } | { tag: "Bar"; } | null; Now, there's this generic function tha ...

Ways to supersede an external TypeScript interface

For my TypeScript project, I am utilizing passport. The provided DefinitelyTyped type definition for passport modifies the Express request to include a user property. However, it defines the user as an empty interface: index.d.ts declare global { nam ...

What is the process for calculating a class property in typescript?

If I were writing this in JavaScript, it would look like: function a(b,c) {this.foo = b; this.bar = c; this.yep = b+c} // undefined b = new a(1,2) // a {foo: 1, bar: 2, yep: 3} However, I've been struggling to achieve the same in TypeScript. None of ...

Automatic generation of generic types in higher-order functions in TypeScript

function createGenerator<P extends object>(initialize: (params: P) => void) { return function (params: P): P { initialize(params) return params } } const gen = createGenerator(function exampleFunction<T>(param: T) { console.lo ...

What is the best way to connect to a JSON key that is consistently returned with a varying or unpredictable name?

I am currently working on an Angular 4.x application where my goal is to showcase a random Wikipedia article. Each time I check the JSON data in Chrome Dev Tools under query/pages, I notice that the pageID always has a different number. The structure of th ...

Troubleshooting problem with ion-input in Ionic 3 regarding the keyboard issue

Issue with Keyboard Overlaying Button In my ionic3 app, I am facing an issue where the keyboard overlaps the "Registrarse" button when it is open, as shown in the image. The button is positioned at the bottom of the ion-content using CSS rules such as pos ...

Having trouble choosing multiple options from autocomplete drop-down with Selenium web-driver in Python

I am currently in the process of automating a webpage built with Angular that features an auto-complete dropdown with numerous elements. My goal is to click on each individual element and verify if it populates all the fields below accordingly. Below is th ...

Steps to obtain the download URL from AngularFireStorage after uploading the file using the getDownloadUrl() method

After successfully uploading images into my firebase storage, I want to retrieve the downloadURL and add it to my firestore database. When console logging "url", I am able to see the desired link. However, I am facing difficulties in using it. When attemp ...

Displaying index.html exclusively using Angular Capacitor

I am currently working on converting my Angular application into an Android application using Capacitor. I have successfully installed Capacitor in my Angular project, which includes routing functionality. Here are the versions of the tools I am using: &qu ...

Can Angular Universal cater to dynamic content needs?

I am considering using Angular Universal for SEO optimization and social media preview purposes. While I understand that it works well with static content, my concern lies with how it handles dynamic content. Specifically, I want search engines and social ...