Setting angular variables by assigning form values

My current reactive form setup looks like this:

this.editform = new FormGroup({
  'username' :  new FormControl(null,[Validators.required]),  
  'password' :  new FormControl(null,[Validators.required]),  
  'full_name' :  new FormControl(null,[Validators.required]),  
  'avatar' :  new FormControl(null,[Validators.required]),   
});

When I use the onSubmit() function, I encounter an issue where changing the submitValue variable also alters the value in the editForm. Here is a snippet of my code:

   onSubmit() {
    const submitValue = this.editform.value
    submitValue.username = 'Jon';
    console.log(this.editform.value.username) // Output : 'Jon'  [The value of editform also changed]
  }

I specifically want to get the form value from the editForm and handle it separately in the submitValue variable without affecting the original form values. Is there a solution to achieve this separation?

Answer №1

let submittedValue = Object.assign({}, this.editform.value);

**Insight:**
  When we use the assignment operator to assign an object to another variable, it works by reference and preserves it.

For example:

let x = {name: 'def', age: 15};
   let y = x;
   y.age = 16;
   console.log(x,y) // Both x.age and y.age are now 16

If you try the following code

let y = Object.assign({}, x);
   y.age = 16;
   console.log(x) // The original value of x remains unchanged because of Object.assign()

**Explanation of Object.assign()**

   In the target object, properties will be overwritten by properties in the sources if they share the same key.

Answer №2

To resolve this problem, you can create a deep copy of the reference using different methods such as

const submitValue = Object.assign({},this. editform.value);

or

const submitValue = JSON.parse(JSON.stringify(this. editform.value));

or by utilizing the lodash cloneDeep function

Answer №3

Indeed! An option is to generate a middle submitContent entity, duplicating the form's content and replacing specific parts of it:

const submitContent = { ...this.formData.value, name = 'Alice' };

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

Tips for ensuring a method is not invoked more than once with identical arguments

I'm grappling with a challenge in JavaScript (or typescript) - ensuring that developers cannot call a method multiple times with the same argument. For instance: const foo = (name: string) => {} foo("ABC") // ok foo ("123") ...

There is no corresponding version available for [email protected] in Angular 6

After cloning a project from git, I attempted to run npm install. However, an error message popped up, as shown in the following link: https://i.stack.imgur.com/pqYbK.png Can someone please explain why this is happening and how I can resolve it? Any help ...

The absence of the 'profileStore' property is noticed in the '{}' type, which is necessary in the 'Readonly<AppProps>' type according to TypeScript error code ts(2741)

I'm currently using MobX React with TypeScript Why am I getting an error with <MainNote/>? Do I just need to set default props? https://i.stack.imgur.com/5L5bq.png The error message states: Property 'profileStore' is missing in typ ...

Creating the upcoming application without @react-google-maps/api is simply not possible

After incorporating a map from the documentation into my component, everything seemed to be functioning correctly in the development version. However, when attempting to build the project, an error arose: Type error: 'GoogleMap' cannot be used as ...

Locate the minimum and maximum values between two inputted dates

I'm looking for a solution that provides strongly typed code. The problem arises when trying to implement solutions from a related question - Min/Max of dates in an array? - as it results in an error. TS2345: Argument of type 'Date' is not ...

Loading data from a remote source in an Angular 6 material table: A step-by-step guide

I'm currently puzzled by the usage of the material table schematic and am struggling to find a solution. It appears that the key aspect lies within the connect() method present in the datasource.ts file. Simply put, this.data is merely an array. / ...

Managing external dependencies in NX & Angular compatible libraries

I am working with a monorepo using NX & Angular where I am publishing some libraries to NPM. In my setup, I have the following structure: apps only_App libs lib_A // v1.0.0 lib_B // v1.0.0 lib_C // v1.0.0 The library lib_A depends on both lib_ ...

When using expressjs and typescript, you may encounter an error stating that the type 'typeof <express.Router>' cannot be assigned to the parameter type 'RequestHandlerParams'

Working on my project using expressjs with the latest typescript definition file and typescript 2.3.4 from https://github.com/DefinitelyTyped/DefinitelyTyped. I've set up a router and want to access it from a subpath as per the official 4.x documentat ...

Angular 4's OrderBy Directive for Sorting Results

I've been working on implementing a sorting pipe based on the code provided in this resource: The issue I'm facing revolves around handling undefined values within my data. The sorting pipe functions correctly when there are no undefined values ...

Extracting information from an Observable in Angular: A comprehensive guide

I am currently working on an Angular application that interacts with a server through RESTful requests, and receives a JSON stream response containing objects of a specific type. The interface for these objects is as follows: export interface Personal { ...

Tips for adjusting the time format within Ionic 3 using TypeScript

I currently have a time displayed as 15:12:00 (HH:MM:SS) format. I am looking to convert this into the (3.12 PM) format. <p class="headings" display-format="HH:mm" > <b>Time :</b> {{this.starttime}} </p> In my TypeScript code t ...

Enhancing validation in Express with custom Typescript types for validation in Express Validator

I encountered an error while using the custom method of the express validator Issue: Argument of type '(userDoc: User | null) => Promise<never> | undefined' is not assignable to parameter of type '(value: User | null) => Promise ...

Suggestions for developing a component library for angular/react modules

I'm currently leading an initiative at my workplace to implement the use of standardized components across all our projects in order to maintain a consistent look and functionality that aligns with our brand. My main concern is figuring out how to eff ...

Enhancing Readability of Public Static Member Variables in Typescript

In my node application, I am utilizing typescript and winston for logging purposes. One key element of my setup is the "Logger" class which consists of a "logger" member and an "init()" function. By exporting this class, I understand that the "logger" memb ...

What is the best way to implement the useCallback hook in Svelte?

When utilizing the useCallback hook in React, my code block appears like this. However, I am now looking to use the same function in Svelte but want to incorporate it within a useCallback hook. Are there any alternatives for achieving this in Svelte? con ...

What is the best way to determine Prisma types across various projects?

My current project has the following structure: dashboard -- prisma-project-1 -- prisma-project-2 -- client-of-prisma-project-1-and-prisma-project-2 This dashboard is designed to merge data from two separate databases and display them in a meaningful w ...

Discover the steps to include the property within the data model in Angular specifically meant for showcasing on the user interface list page

class UserIdentity { public uniqueID: string; public fullName: string; public bio: string; public service: string; public groupID: string; public userID: string; public secretKey: string; constructor(details?: any) { this.uniqueID = &a ...

I am attempting to incorporate an NPM package as a plugin in my Next.js application in order to prevent the occurrence of a "Module not found: Can't resolve 'child_process'" error

While I have developed nuxt apps in the past, I am new to next.js apps. In my current next.js project, I am encountering difficulties with implementing 'google-auth-library' within a component. Below is the code snippet for the troublesome compon ...

Implement the properties encapsulation design pattern

In need of a method to control document activation logic, where activating a document involves adding it to a list of activeDocuments and setting a flag to true. Direct access to the isActive property should be prohibited. class DocumentService { pr ...

To continue receiving rxjs updates, kindly subscribe if the specified condition is met

Is there a way to check a condition before subscribing within the operator chain? Here's what I have: // parentElem:boolean = false; // the parent elem show/hide; let parentElem = false; // inside the ngAfterViewInit(); this.myForm.get('grandPa ...