updating an object using its instance in angular: step-by-step guide

Having multiple nested arrays displaying data through HTML recursion in Angular, I am faced with the task of updating specific fields. Directly editing a field is simple and involves assigning its instance to a variable.

arr=[{
    "name":"field-1",
    "fields":[
        {
            "name":"Field-2",
            "fields":[]
        },
        {
            "name":"field-3",
            "fields":[
                {
                    "name":"field-3",
                    "fields":[]
                }
            ]
        }
    ]
}]

If I want to edit a field, I simply assign its instance to a variable.

<ng-template #recursion let-data="data">
    <ng-container *ngFor="let item of data">
        <div>
            {{item.name}}
            <button (click)="edithThis(item)">Edit</button>
        </div>
        <div *ngIf="item.fields && item.fields.length">
            <ng-container *ngTemplateOutlet="recursion;context:{data:item.fields}"></ng-container>
        </div>
    </ng-container>
</ng-template>
export class Component{

    data_to_edit: any;

    edithThis(selected: any) {
        this.data_to_edit=selected
    }

}

After modifying data_to_edit, the original value changes as well. To enable reverting back to the old value upon cancellation, two variables are utilized.

export class Component {

    data_to_edit: any;
    instance_of_data: any;

    edithThis(selected: any) {
        this.data_to_edit = { ...selected }
        this.instance_of_data = selected
    }

}

One variable is used for modification, while the other ensures that the original value is updated after confirming the change.

Answer №1

Currently, I am storing the data in two separate values. One value holds the edited data, while the other serves as a reference point (which can be used to update its value in heap memory). When the user clicks on confirm, I update the reference using a simple loop.

export class Component {

    data_to_edit: any;
    instance_of_data: any;

    edithThis(selected: any) {
        this.data_to_edit = { ...selected }; // without reference
        this.instance_of_data = selected; // storing for reference
    }

    /**
     * Updates the reference of the variable with the edited data
     */
    updateData() {
        for (let key in this.instance_of_data) { // for all old keys
            if (!(key in this.data_to_edit)) { // If a key is removed while editing, remove it from the reference 
                delete this.instance_of_data[key]
            } else { // Otherwise, update the reference value with the current data
                this.instance_of_data[key] = this.data_to_edit[key]
            }
        }
    }

}

If the user clicks on cancel, I can disregard the changes. I'm open to alternative approaches. Thank you.

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

What's stopping the error exception from showing up on the client side?

Here's the scenario: I have an action method called SavePoint that contains some logic and throws a System.ArgumentException with the message "Error, no point found". Additionally, there is an ajax function named saveFeature which makes a GET request ...

Creating a CSS triangle that smoothly transitions between two different colors

Is it possible to create a triangle in CSS that smoothly transitions between two colors without relying on a hover state? .arrow-down { width: 0; height: 0; border-left: 20px solid transparent; border-right: 20px solid transparent; b ...

Deactivate click events in the container div

Here is the html code snippet that I am working with: <div class="parent" ng-click="ParentClick()"> . . . <div class="child" ng-click="ChildClick()"> Some Text </div> </div> When clicking on Som ...

Is there a way to specifically call the last promise in a loop?

I'm new to promises and could use some help. I have a situation where promises are resolving randomly, how can I ensure that the last promise in the loop is resolved after the full loop executes? For example, if this.selectedValues has 4 values, som ...

Executing Angular async routing functions outside of the ngZone allows for more efficient

The routing function was called within a service and I am encountering the following warning message: Navigation triggered outside Angular zone, did you forget to call 'ngZone.run()'? However, I cannot simply call this.ngZone.run(...) because I ...

What happens when an AJAX request doesn't have a success field?

Is it possible to execute an ajax call without specifying a success function? $.ajax({ type: "POST", url: "/project/test/auto", data: data, // no success function defined here }); My reasoning for this is that I have PHP code that insert ...

Sit tight as we prepare all static assets for loading on the screen

Currently, I am developing a vuejs application that will incorporate video elements. To enhance user experience, we are interested in preloading these videos upon the initial loading of the web application. I am considering using a listener like, documen ...

Utilizing React JS Styled-Components to Import Images from the Public Directory

I've been attempting to set the image as a background-image from the public folder using styled-components. I've tried the following: import styled from "styled-components"; import Background from 'process.env.PUBLIC_URL + /images/ ...

Custom type checker that validates whether all properties of a generic object are not null or undefined

In an attempt to create a user-defined type guard function for a specific use-case, I am faced with a challenge: There are over 100 TypeScript functions, each requiring an options object. These functions utilize only certain properties from the object wh ...

Switching between light and dark themes in a Next.js application with Ant Design v5 theme toggle

In my Next.js application using Ant Design v5, I am working on implementing a dynamic theme toggle to switch between light and dark modes. The issue I'm facing is that the initial theme settings work correctly, but subsequent changes to the isDarkMode ...

Adding a new property to the Express request object type: what you need to know

Recently, I developed a custom middleware that executes specific logic tasks. It operates by transforming the keys to values and vice versa within the req.body. Both the keys and values are strings, with built-in validation measures in place for safety. T ...

javascript issue with onchange query

The JavaScript snippet below is included in the head section of my file. <?php echo "<script language='JavaScript'>\n"; echo "var times = new Array();\n"; echo "times[0] = 0;\n"; foreach($times as $time) { echo "times[". ...

The addListener method in Google Maps iterates n times for a specific number of repetitions

When looking at the code below, the GetPropBasedOnRadius(); method loops for a certain number of times. I want to call that method only when the dragging event is completed. However, I am unsure how to do this. Any assistance on this matter would be great ...

Resolving TypeError: matchesSelector method is not recognized within React component

I am currently integrating masonry-layout from the official website to create a masonry grid within my component. However, I encountered an issue where clicking on a rendered element triggers the error message TypeError: matchesSelector is not a function. ...

Utilizing TypeScript for messaging in React Native and React

I have encountered a specific issue with my React projects. When using npx without Typescript, I receive error messages as shown in the following screenshots: https://i.sstatic.net/g68ho.png https://i.sstatic.net/Kmye5.png Interestingly, in my React Nat ...

Guide on accessing checkbox id in Vue3 and determining its checked status

<div> <input type="checkbox" class="delete-checkbox" :id=this.products[index].sku @click="setDelete(this.products[index].sku)" /> </div> I'm currently working on a Vuex applicatio ...

A space designated for numerous receivers

Is there a way to create a field that contains other elements, similar to sending messages to multiple users in a social network? https://i.stack.imgur.com/P9e24.png I attempted to understand the code for this, but it's quite complex. If anyone could ...

What is the appropriate utilization of the await keyword within concise if-else statements in JavaScript?

Along with transitioning away from jQuery, my main focus is to make my code more efficient. In large scale enterprise applications, the excessive use of jQuery and JavaScript can become problematic. I have decided to switch back to vanilla JavaScript for ...

Angular: monitoring changes in HTML content within a Component or Directive

I have a situation where I am retrieving HTML content from a REST endpoint using a directive and inserting it into a div element using [innerHTML]. Once this HTML content is rendered, I would like to manipulate it by calling a global function. My approach ...

How come the values keep appearing without any loops or subsequent calls being made to the PHP file?

Here is a demo example showcasing 'Server Sent Events(SSE)': Embed HTML code(index.html) : <!DOCTYPE html> <html> <body> <h1>Receiving server updates</h1> <div id="result"></div> <script> if(type ...