LLaza
LLaza

Reputation: 379

how to reset form group array in angular

I have a form array, but if I push another form this have setted the validations of previus form.

in this example [https://plnkr.co/edit/ApCn3YicMjfm2vhSOudj?p=preview][1]https://plnkr.co/edit/ApCn3YicMjfm2vhSOudj?p=preview you can see that the second form shows the name validation, how can I solve this?

Upvotes: 0

Views: 751

Answers (2)

constlhq
constlhq

Reputation: 204

All the forms share the same FormGroup here,named "user",which kept form data and states ,so you can either create a separate FormGroup for each Form or reset the value of "user" each time in the submit method,but the latter will make the current form lost its data either.Cause they shared the "user".

onSubmit({ value, valid }: { value: User, valid: boolean }) {
console.log(value, valid);
this.data.push(value)
this.user = this.fb.group({
  name: ['', [Validators.required, Validators.minLength(2)]],
  account: this.fb.group({
    email: ['', Validators.required],
    confirm: ['', Validators.required]
  })
});
console.log(this.data)

}

Upvotes: 0

DeborahK
DeborahK

Reputation: 60626

Based on the comments above and messing around with the plunker I think I finally see what you are asking.

The issue has to do with how forms work.

Forms have two pieces:

1) The form element itself displayed in the view.

2) The form data structure, which for reactive forms as you have are defined in the component code with the this.user variable. It is this data structure that tracks the forms values and validity state.

In looking at your code your ngFor is creating multiple form elements (#1 above) but using the same form data structure (#2 above). So the multiple forms will always show the same values and have the same validation state.

You'd need to build a formArray and create an entry in that array for every "form" you create.

I have an example of a form array here: https://github.com/DeborahK/Angular2-ReactiveForms

Upvotes: 1

Related Questions