Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trigger Submit event of Angular Form from Parent

I have a child component which has a reactive form and from parent when I click on submit, I want it to trigger submit functionality which includes validations on submit.

parentComponent

export class ParentComponent {
  @ViewChild('childComponent') childComponent: ChildComponent
  
  submit(): void {
     this.childForm.triggerSubmit();
  }
}

parent Html

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<child-component #childComponent></child-component>
<input type="button" value="submit" (click)="submit()">

childComponent

export class ChildComponent {
  @ViewChild('myForm') myForm: NgForm;
  myFormGroup: FormGroup;

  constructor(private fb: FormBuilder) {
    this.initializeForm();
  }

  initializeForm(): void {
    this.myFormGroup = this.fb.group(
      {
        name: ['', { validator: Validators.required}]
      }, { updateOn: 'submit' }
    );
  }

  submitForm() {
    console.log(this.myFormGroup.value);
  }

  triggerSubmit() {
     this.myForm.ngSubmit.emit();
  }
}

childComponent Html

<form
#myForm="ngForm"
[formGroup]="myFormGroup"
(submit)="submitForm()"
>
<label for="float-input-name">Device Name</label> <br />
<input
   formControlName="name"
   id="float-input-name"
   type="text"
   />
<ng-container
   *ngIf="
   myFormGroup.get('name')?.invalid &&
   myFormGroup.get('name')?.errors &&
   (myFormGroup.get('name')?.dirty || myFormGroup.get('name')?.touched)
   "
   >
   <small
      class="text-danger block"
      *ngIf="myFormGroup.get('name')?.hasError('required')"
      >
   This field is required.
   </small>
</ng-container>
</form>

triggerSubmit method is called but submit event of form is not getting triggered. Once it gets triggered, ideally submitForm method should be triggered. Any help will be appreciated. Thanks!

>Solution :

In child-component html you should change event name to (submit) to (ngSubmit)

<form #myForm="ngForm" [formGroup]="myFormGroup" (ngSubmit)="submitForm()" >
....
</form>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading