0
votes

Is it possible to pass the ngSubmit function as a parameter? I created a component that receives an Id and the name of the ngSubmit function, but how do I put this parameter on the template?

I have a component called validation-form

validation-form.component.html

<form [id]="formId" method="post" novalidate [(ngSubmit)]="">
    <ng-content></ng-content>
</form>

My validation-form.component.ts has

  @Input() formId: string;
  @Input() submit: string;

I pass this values like this

<validation-form formId="ResetPasswordForm" submit="resetPassword()">
</validation-form>

I want to put the value of @Input() submit: string; to to the (ngSubmit). How can i do this?

1
You will have to pass the appropriate function as a reference and not by method name (i.e. <validation-form ... [submit]="resetPassword">). The function will not be accessible by name outside of your component that is using <validation-form>. - Daniel W Strimpel
I'm starting to study angular, so if you could give me more details it would be great. Using [submit]="resetPassword" will get the reference of the method? And how do I use this reference on the ngSubmit? Thx for answering XD - Testador
I fail to see the point of that component, since it doesn't do anything other than a standard form already does. But submit shouldn't be an input. It should be an output. Your validation form component should emit an event to its parent when the form is being submitted. - JB Nizet
I created this component because i'm using a jquery validation lib that already have all the validation and messages I need. - Testador

1 Answers

0
votes

It looks like you want to handle the validation or submission on parent component rather than child component validation-form.

To achieve this, you can use @Output decorator. It will propagate event from child to parent. Here is the code which can help you to achieve the same.

validation-form.component.ts

  @Input() formId: string;
  @Input() submit: string;
  @Output() submit = new EventEmitter();

  public submit(){
     this.validate.emit(this.formId); //<-- you can pass the object if you need more info to pass.
  }

validation-form.component.html

<form [id]="formId" method="post" novalidate (ngSubmit)="submit()">
    <ng-content></ng-content>
</form>

Parent Component.html

<validation-form formId="ResetPasswordForm" (submit)="resetPassword($event)">
</validation-form>

Parent Component.ts

public resetPassword(formId){
  console.log("Form Id ", formId);
}