Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save tree form recursively and emit event on finish

I have a form with nested forms like that

Form 1
-- Form 1.1
-- Form 1.2

What I need is save Form 1, then save Form 1.1 and Form 1.2 using Id retrieved from saving Form 1 and after that emit that all children are saved.

I have to do this dynamically since the depth of this form is much bigger.

How is it better to perform this action?

I've tried to place a directive on children component's tags however I'm unable to read these components. These components are different and may be dynamic, so I cannot use @ViewChild on components.

I want to observe these child components for the sake of knowing how many events should be emmitted before telling parent component that everything is ready.

For now I can only think of a some service that would contain counts for every parent.

Update #1

Here is a StackBlitz and is a simplified version of what I have. In real app there is a dynamic component presence as well as dynamic parameter names (the ones I have to pass from parent to connect children) and nesting level of the form.

I've tried to cover workflow details with comments.

TL;DR I need to save all Persons, then save each Person's names using personId as an additional parameter to connect them in DB, after all form part are saved I need to report parent form that everything is ready.

like image 540
Sergey Avatar asked Nov 24 '25 08:11

Sergey


1 Answers

You have everything you would need at the app.component.ts level, to iterate through the tree recursively and complete your save logic without any state at the child level.

Use your Observable logic in the submit() method to retrieve the ID from the first save, once you receive that ID proceed to iterate over the next level down values in the form and complete the next save. Once all of your conditions are met at the app.component.ts level close the form.

submit() {
    // Here goes an initial form submit which returns an ID of saved form
    console.log('submit a form');
    let persons: Person[] = this.formGroup.value.persons;
    for (let person of persons) {
      console.log('Saving person with Birthdate: ' + person.birthDate)
      for (let name of person.names) {
        console.log('Saving nameObject: ' + JSON.stringify(name))
      }
    }
}
like image 99
Marshal Avatar answered Nov 25 '25 21:11

Marshal