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
<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
*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!
CodePudding user response:
In child-component html you should change event name to (submit)
to (ngSubmit)
<form #myForm="ngForm" [formGroup]="myFormGroup" (ngSubmit)="submitForm()" >
....
</form>