dev_054
dev_054

Reputation: 3718

Angular: Create a new form based on another form

Let's suppose that have a form, like this (my real form is more complicated):

this.group = this.formBuilder.group({
  name: '',
  email: ''
});

My form configuration works so far... now I'm wanting to change some values before submit the form to the API... and since I want to keep the reference and value of the original form` untouched, I prefer to clone the form. So I'm trying to do it like this:

const cloneGroup = this.formBuilder.group(this.group.controls);
// Shouldn't it create a form with a new reference, 
   since it creates a new FormGroup internally?

The problem is that once I call patchValue method in cloneGroup, this.group also changes, and ofc I want only the clone to be changed.

Here's the demo that you can play to see better my question.

The question is: Why? If I created a new form isn't it supposed to create a really new form?

PS: As explained above, I don't want to clone only the values because I want keep the reference and values of the original form (to call some methods of the form itself), so just cloning the value isn't an option.

Upvotes: 2

Views: 2713

Answers (1)

snorkpete
snorkpete

Reputation: 14564

I'm not quite sure what you're trying to achieve with cloning the form, but if you're just focused on having two independent forms One approach of getting your clone to work is to focus on re-using the form configuration, not the form controls themselves. Then you can use getValue and setValue against your clone to update it with the values of the original before you go off and make changes to the clone.

So, you can do something like:

let formConfig = {
   name: '',
   email: ''
};

this.group = this.formBuilder.group(formConfig);
this.clone = this.formBuilder.group(formConfig);

.......

// and then later when you want to use the clone
this.clone.setValue(this.group.getValue());

// and then you can update your clone..
this.clone.patchValue(....);

The above approach should work fine once you don't need to keep your clone realtime-synced with the original form but instead can update it at a specific time. If you need realtime-sync, it becomes slightly more complicated, but the same basic logic would apply - subscribe to the original's valueChanges, and on each event, update your clone.

Upvotes: 1

Related Questions