Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submit in custom Angular button component does not submit form

I have extracted the submit button into a seperate component. Now, the form is not submitted/the submit function is not called anymore as ngSubmit is not triggered.

<form [formGroup]='form' (ngSubmit)='submit(form.value)'>
   ...
   <app-submit-button></app-submit-button>
</form>

The problem is that the button in my custom component app-submit-button triggers a function call on click. The submit event is not further propagated to the parent component and thus its submit function is not executed. However, when I remove (click)='submit()' from the child component, form submit works.

<ng-container [ngSwitch]='state'>
  <button *ngSwitchCase='buttonState.Idle' (click)='submit()'
    type='submit'>{{idleText}}</button>
  ...
</ng-container>

I tried it with and without type='submit' on app-submit-button and on the button itself.

I got it working with

<app-submit-button (click)='submit(form.value)'></app-submit-button>

and removing ngSubmit. I would like to know if it is the proper way or if this behaves differently then using ngSubmit.

like image 934
Matthias Sommer Avatar asked Apr 08 '26 05:04

Matthias Sommer


1 Answers

I think you should not make a different component just for a button. The problem is you can not pass an event from parent to child. both of the submit functions are different since they belong to different classes(one is in parent component and other is in the child). you can either create an event in your app-submit-button component and emit the event on button click. like this in your app-submit-button typescript file

@Output()
submitEvent = new EventEmitter<>();
submit(): void {
submitEvent.emit();
}

then handle the event in the parent component html file like this

<app-submit-button (submitEvent)="submit(form.value)"></app-submit-button>

It will trigger an event in the child component and parent will act on that event. But still it is bad practice to create a different component just for a submit button. You should use the button directly in form without using a child.

like image 79
Torab Shaikh Avatar answered Apr 09 '26 22:04

Torab Shaikh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!