1

I have a FormGroup that includes FormArray. When the user fulfills the form, he/she can dynamically add new controls. For this purpose I use FormArray. But after the form was submitted all the controls that the user added remained on the page. So I want to keep only one control in the FormArray after clicking the submit button.

Code is the following:

  workoutForm = this.fb.group({
    name: ['', Validators.required],
    completed: [false],
    exercises: this.fb.array([this.createExercise()])
  })

  createExercise(): FormGroup {
    return this.fb.group({
      name: ['', Validators.required],
      completed: [false]
    })
  }

  onSubmit() {
   // Here I want to delete all elements from the exercises and to keep only one
    this.workoutForm.reset();
  }

UI (don't judge it. No CSS yet :) )

enter image description here

You can see there are 2 Exercise fields now. I want it to be only 1 after I clicked submit. How can I do so?

1 Answer 1

2

Actually, I just solved it this way:

I added a getter for my exercises (I will need it later in my code).

get exercises() {
  return this.workoutForm.get('exercises') as FormArray;
}

Then I cleared all exercises - this removes all elements from the FormArray.

this.exercises.clear();

And then I added a field again

  addExercise() {
    this.exercises.push(this.createExercise());
  }

onSubmit() {
  ///...some code
  this.addExercise();
}

So the overall code looks like this:

workoutForm = this.fb.group({
    name: ['', Validators.required],
    completed: [false],
    exercises: this.fb.array([this.createExercise()])
  })

  get exercises() {
    return this.workoutForm.get('exercises') as FormArray;
  }

  createExercise(): FormGroup {
    return this.fb.group({
      name: ['', Validators.required],
      completed: [false]
    })
  }

  addExercise() {
    this.exercises.push(this.createExercise());
  }

  onSubmit() {
    this.workoutForm.reset();
    this.exercises.clear();
    this.addExercise();
  }
Sign up to request clarification or add additional context in comments.

2 Comments

even you could create your own array, this.excersisesArray.push({ name: ['', Validators.required], completed: [false] }) , and later update it with shift()
Your solution works on Angular 16 =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.