Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - Submit a form programmatically

Angular - Submit a form programmatically.

I have a form group on the HTML and I want the component to submit the form's action with an email field in a post method. Instead of using a normal submit button.

Below's testMethod gets called from another button. In this method, I want to post the testForm. It has to be posted old school way as it needs an action.

This is my HTML:

<form
  [formGroup]="testGroup"
  [action]='actionLink'
  method='POST'
  #testForm>
   <input name='Email' type='hidden' [value]='currentUserEmail'>
</form>

This is my Component TS file attempt:

  @ViewChild('testForm') testFormElement;

  public currentUserEmail: string = '';
  public testGroup = this.formBuilder.group({
    Email: ''
  });


  public testMethod(): void {

      // Below: This currently doesnt seem to do anything.
      this.testFormElement.ngSubmit.emit();
  }
like image 943
AngularM Avatar asked Aug 30 '25 18:08

AngularM


1 Answers

You can use ngNoForm with your form to remove ngForm handling and to add plain javascript handler.

you can use your code as follows:

Html file.

<form ngNoForm
  [formGroup]="testGroup"
  [action]='actionLink'
  method='POST'
  #testForm>
    <input name='Email' type='hidden' [value]='currentUserEmail'>
</form>

Ts File.

@ViewChild('testForm') testFormElement;

public currentUserEmail: string = '';
public testGroup = this.formBuilder.group({
  Email: ''
});

constructor(formBuilder: FormBuilder) {
}    

public testMethod(): void {
  this.testFormElement.nativeElement.submit();
}
like image 107
faizan baig Avatar answered Sep 02 '25 08:09

faizan baig