How To Submit Form Data In Angular


Today we'll be learning how to work with Angular forms.

Specifically how to submit data via a reactive Angular form.

Our goal is to handle the data from an Angular form when they hit ENTER or click on the submit button.

We'll start with our component's Typescript code.

import { Component } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';

@Component({
  selector: 'app-login-form',
  standalone: true,
  imports: [ReactiveFormsModule],
  templateUrl: './login-form.component.html',
  styleUrl: './login-form.component.css'
})
export class LoginFormComponent {
  loginForm = new FormGroup({
    email: new FormControl('', Validators.email),
    password: new FormControl('', Validators.minLength(8))
  });

  submit() {
    if (this.loginForm.invalid) {
      return;
    }

    console.log(this.loginForm.value);
  }
}

You'll see that we've declared a reactive form with two inputs - email and password text fields - with some validators.

We've also defined a submit function that will be called when our form is submitted.

From this function we can change app states, call backend API's or whatever else needs to be done with our form.

Now let's work on our template (HTML) code.

<form [formGroup]="loginForm" (ngSubmit)="submit()" >
    <input type="email" name="email" placeholder="email" formControlName="email">
    <br/>
    <input type="password" name="password" placeholder="password" formControlName="password">
    <br/>
    <button type="submit" [disabled]="loginForm.invalid">Login</button>
</form> 

The key piece here, when submitting an Angular form, is the ngSubmit function.

This function will trigger the submit() function any time the HTML form is submitted by our users.

And that's how to submit form data when working with Angular reactive forms.

signature

Daniel Kreider