Search code examples
angulartypescriptangular6angular-componentsangular-forms

How to Send FormGroup Object as Output to Parent Component from child component n Angular


I'm working in forms and I have two components: my child component contains this formGroup Object :

employeeForm : FormGroup;
this.employeeForm = new FormGroup({
       firstName:new FormControl(),
       lastNAme:new FormControl(),
       email:new FormControl()
    });

the child Component conatins just a small part of the form and the parent componant, contains the global form with submit button..

my issue is: I want in the Parent Component when I click on submit button I get the form group from my child component and push it to my global form in my parent component.

I add output in my child component :

@Output() onFormGroupChange: EventEmitter<FormGroup> = new EventEmitter<FormGroup>();

but I don't know how to let the submit button in parent Comp take the FormGroup object from my child component and proceed to push data...

do you have any idea on how to achieve this?

Thanks in advance.

Best Regards.


Solution

  • Do something like this in child component:

    import { Component, OnInit, Output, EventEmitter } from '@angular/core';
    import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
    
    @Component({
      selector: 'app-child',
      templateUrl: './child.component.html',
      styleUrls: ['./child.component.css']
    })
    export class ChildComponent implements OnInit{
      @Output() private onFormGroupChange = new EventEmitter<any>();
    
    
      employeeForm = new FormGroup({
           firstName:new FormControl(),
           lastNAme:new FormControl(),
           email:new FormControl()
        });
    
      public ngOnInit() { 
        this.onFormGroupChange.emit(this.employeeForm);
      }
    
    
    }
    

    And parent component: this.formCheck is actual formGroup we can use in html.

    import { Component, OnInit } from '@angular/core';
    import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
    
    @Component({
      selector: 'app-parent',
      templateUrl: './parent.component.html',
      styleUrls: ['./parent.component.css']
    })
    export class ParentComponent { 
      formCheck :any  = '' 
      public onFormGroupChangeEvent(_event) {
        this.formCheck = _event;
        console.error(_event, this.formCheck['controls'])
      }
    }
    

    Demo