Home > OS >  How to get the form from a child component and emit to the parent
How to get the form from a child component and emit to the parent

Time:12-14

I have Parent component with a two childs. I want to get the form from the childs and send to the parent everytime that is changed.

I have the parent form like this:

 profileForm = new FormGroup({
    firstName: new FormControl(''),
    lastName: new FormControl(''),
    address: new FormGroup({}),
  });

child 1 component:

 @Output() onFormEmit = new EventEmitter<any>();
  form = new FormGroup({
    child1Key1: new FormControl(''),
    child1Key2: new FormControl(''),
    child1Key3: new FormControl(''),
  });

  ngOnInit() {
    this.onFormEmit.emit(this.form);
  }

child 2 component:

 @Output() onFormEmit = new EventEmitter<any>();
  form = new FormGroup({
    child2Key4: new FormControl(''),
    child2Key5: new FormControl(''),
  });

  ngOnInit() {
    this.onFormEmit.emit(this.form);
  }

After the emit, I want the form to be like this:

  profileForm = new FormGroup({
    firstName: new FormControl(''),
    lastName: new FormControl(''),
    address: new FormGroup({
      child1Key1: new FormControl(''),
      child1Key2: new FormControl(''),
      child1Key3: new FormControl(''),
      child2Key4: new FormControl(''),
      child2Key5: new FormControl(''),
    }),
  });

And I also want to send the nested form to the child as a Input, so I need to keep the alive conversation between the forms.

this is what I have until now: StackBlitz

CodePudding user response:

It looks to me like 'nested forms' might be what you're looking for, where the parent formGroup is passed as an input to the child component - the controls in the child are added to that

There's three approaches described in the linked article, the first one is doing the above:

CodePudding user response:

So, why don't you emit child's form.getRawValue() after each change and when you get this data on the parent's event listener you iterate through object keys and values setting the result form fields ? In the end of the callback just send updated form to children again.

  • Related