1
votes

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.

1
Why don't you call submit from within the click function then?Can
Did you find a solution for this? The suggestion above doesn't work as the errorStateMatcher doesn't set form.submitted to trueRichard

1 Answers

0
votes

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. I hope this helps. Happy coding ;-)