Angular form submit event firing twice between parent and child components
10,002
You have used a reserved word 'submit' on child component as decorator function and attribute. So if you have a form in a parent component, (submit)
(which is equivalent of (ngSubmit)
) is fired at the same time as the event from the child.
Change it for something else, like this:
<child-form (childSubmit)="parentSubmit($event)"></child-form>
and in child component:
@Output() childSubmit = new EventEmitter<any>();
...
childFormSubmit() {
if (this.childForm.valid) {
console.log('Child Form Submit')
this.childSubmit.emit();
}
}
Here is a working DEMO
Author by
Charlie Kou
Updated on June 16, 2022Comments
-
Charlie Kou almost 2 years
I have a strange problem where by the form submit event of my child form is firing twice on my parent form.
child.component.html
<form [formGroup]="childForm" (ngSubmit)="childFormSubmit()"> ... </form>
child.component.ts
@Component({ selector: 'child-form', templateUrl: 'login.component.html', }) export class ChildComponent { @Output() submit = new EventEmitter<any>(); public childForm: FormGroup; childFormSubmit() { if (this.childForm.valid) { console.log('Child Form Submit') this.submit.emit(this.childForm.value); } } }
parent.component.html
<child-form (submit)="parentSubmit($event)"></child-form>
parent.component.ts
@Component({ selector: 'parent', templateUrl: 'parent.component.html', }) export class ParentComponent { constructor() { } parentSubmit(event: any) { console.log('Parent Submit'); } }
Submitting the child form results in the following in the console output:
Child Form Submit Parent Submit Parent Submit