Search code examples
angularangular-httpclientangular-reactive-forms

Angular - Send Form Data on Form Submit with updated form values


I have a form with an action url

<form 
  ngNoForm 
  id="login-form" 
  [formGroup]="loginForm" 
  (submit)="onSubmit()" 
  [action]='actionUrl' 
  method='POST'>
  <div class="form-group">
    <label class="label-input" for="email">username</label>
    <input 
      type="text" 
      formControlName="username" 
      name="username" 
      id="username" 
      [ngModel]="username" />
  </div>
  <div class="form-group">
    <label class="label-input" for="password">Password</label>
    <input 
      [type]="password" 
      formControlName="password" 
      name="password" 
      class="form-control" />
  </div>
</form>

in my component.ts i have this:

onSubmit() {
  this.username = 'updatedusername';
  this.testFormElement.nativeElement.submit();
}

I want to send to action url the updateusername and always send the value entered in ui.

How can I send the new value for and username input? I need to add additional values to username that user has been entered.


Solution

  • Judging from your template code, you're already using the ReactiveFormsModule.

    You can get the value of the form using this.loginForm.value

    Send your API call on the onSubmit method using HttpClient, like this:

    onSubmit() {
      this.http.post('your-api-url-here', this.loginForm.value)
        .subscribe(res => console.log(res));
    }
    

    Here's a Working Sample StackBlitz for your ref.