Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Parent Form with Child Form Component, how to Let Child Know when Parent is submitted?

I am using a Parent Form with a Child Component Form as in this manner. https://stackoverflow.com/a/59310301/15435022

How do I let the Child Component know when Parent Form has button Ng submitted? The parentForm variable is in child component as variable. Is there a way, I can tell with parentFormGroup as an event?

When the child form knows, I want to calculate some intricate values (not in the form), and send them to the parentComponent.

Parent Component:

 ngOnInit() {
    this.parentForm = this.fb.group({
       'customerName': [null, [Validators.required]],
       'phoneNumber': [null, [Validators.required]],
    })

 <form [formGroup]="parentForm" (ngSubmit)="onSubmit()">
    <app-child [form]="parentForm"></app-child>
    <button type="submit">Purchase</button>
 </form>

Child Component:

Need to know in this component, when parentForm is submitted.

@Input() parentForm: FormGroup;

ngOnInit() {
    this.parentForm.addControl('address', new FormControl(Validators.required));
    this.parentForm.addControl('city', new FormControl(Validators.required));
 }
like image 211
mattsmith5 Avatar asked Nov 18 '25 02:11

mattsmith5


1 Answers

You can inject FormGroupDirective inside child component then subscribe ngOnSubmit event inside child component to listen parent form submission.

child.component.ts

 constructor(private fg: FormGroupDirective){
    this.fg.ngSubmit.subscribe(()=>{
      console.log('listen submit');
    })
  }

Working Example

like image 71
Chellappan வ Avatar answered Nov 19 '25 20:11

Chellappan வ