0

I have a form in Angular 5 structured like so: There are a bunch of rows that each contain data about a single entity. These rows use template side form validation and have a submit handler that saves the entity.

All of these rows are wrapped in a larger form that represents the collection of entities that we care about.

Now, I want the user to be able to push one button that will submit all of the child forms for ease of use. I could just call all of the submit handlers from the parent, but this wouldn't trigger the template's form validation. Is there any way for the parent form to trigger the submission of all the child forms in the same way as if the user had pressed save on each row?

Thanks.

VivaLaPanda
  • 809
  • 7
  • 24

1 Answers1

0

I've figured out a partial solution, but I'm not going to mark this as answered because I feel like there is/should be a better way.

I added a template name #taskForm="ngForm" to the subforms. Then in the subforms I added @Input() submit: boolean; and @ViewChild('taskForm') taskForm: FormGroupDirective;.

I then extended the component to implement OnChanges and added the following lifecycle function

ngOnChanges() {
  if (this.submit === true) {
    this.taskForm.ngSubmit.emit();
    this.submit = false;
  }
}

The parent then just iterates over the ngFor children and sets the submit input parameter to true when the parent form is submitted. This mostly accomplishes what I want, but it still feels sort of hacky.

Edit: Code to submit the form programatically was found here: https://stackoverflow.com/a/38054632/4951118

VivaLaPanda
  • 809
  • 7
  • 24