How to Send FormGroup Object as Output to Parent Component from child component n Angular
You can pass the parent form to child component:
<form [formGroup]="parentForm">
<child-form [form]="parentForm"></child-form>
<button (click)="submit()">Submit</button>
</form>
In child-form.component.ts, you can use addControl:
@Input() form; // this is parentForm
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.form.addControl('firstName', new FormControl('', Validators.required));
}
When click submit, you'll be able to get the form data from child component too:
this.parentForm.value
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