Build angular 13 forms with example

Build angular 13 forms with example

By developing a simple contact form example, we'll understand how to create and work with forms in Angular 13.

We'll look at how to use the ngForm, ngSubmit, and ngModel directives to create a template-based form, as well as the FormGroup and FormBuilder classes to create a reactive form.

We'll be using https://stackblitz.com/ as our online IDE. Simply register for an account using your GitHub account and START A NEW APP based on Angular from ready templates. Your Angular project will be based on the latest Angular 13 version.

For working with forms, Angular 13 and previous versions provide two approaches:

  • The template-based approach; - The template-based approach.

There is no better methodology for small projects; simply pick the one that is most handy for you! However, it is recommended to use reactive forms for larger projects because they scale better.

Create an angular 13 template-based form

Let's begin with the template-based approach by creating a simple angular 13 form. Let's play around with some configurations.

Import the angular forms module

Open the src/app/app.module.ts file and import the FormsModule then we add it to the imports array:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';

@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

If you are using Stackblitz, the FormsModule class is already imported in the project.

That's all you need to do in order to work with template-based forms.

Add angular forms directives

Next, open the src/app/app.component.html file and add the following content:

<h1> Angular 13 template-based contact form by example </h1>

<form #myform = "ngForm" (ngSubmit) = "onSubmit(myform)" >
  <input type = "text" name = "fullName" placeholder = "Your full name" ngModel>
  <br/>

  <input type = "email" name = "email" placeholder = "Your email" ngModel>
  <br/>

  <textarea name = "message" placeholder = "Your message" ngModel></textarea>
  <br/>
  <input type = "submit" value = "Send">
</form>

We can create our form completly in our Angular template. We first add a template reference variable to the form and assign the ngForm key to it using the #myform = "ngForm" syntax. This will allow us to access the form via the myform reference.

Note: The #myform = "ngForm" syntax doesn't create a template based form but only a local templae variable that will allow us to work with the form object. In fact, the form was automatically created when you imported FormsModule in your project .

Next, we bind the ngSubmit event to the onSubmit() method (Which we'll add to our component next) and we pass in the form object (via the local template variable)

Next, we register the child controls with the form. We simply add the NgModel directive and a name attribute to each element.

According to the docs:

NgForm creates a top-level FormGroup instance and binds it to a form to track aggregate form value and validation status. This is done automatically when FormsModule is imported.

Submit the angular 13 template form

Next, add the onSubmit() method to the component. Open the src/app/app.component.ts file and add the following code:

import { Component } from '@angular/core';
import {NgForm} from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

  onSubmit(form: NgForm) {
      console.log('Your form data : ', form.value);
  }
}

We passed in the reference to the NgForm object that represents our form to the onSubmit() method and we can use it to access various properties like value which provides a plain JS object that contains the attributes of the form and its data. In this example, we simply print the form value in the console but in a real world situation, we can use it to send the data to a server via a POST request.

You can see all the available methods of NgForm from the docs.

After, adding some CSS styles from this pen, this is a screenshot of our form UI:

Angular 13 Form Example

This is the live project:

Create an angular 13 reactive form

After creating our angular 13 contact form using the template-based approach, let's look at how we can create the same example using the reactive approach.

Go to the src/app/app.module.ts file and import FormsModule and ReactiveFormsModule as follows:

import  {  FormsModule,  ReactiveFormsModule  }  from  '@angular/forms';

Following that, add them to the imports array of the application module:

// [...]

@NgModule({
  imports:      [ BrowserModule, FormsModule, ReactiveFormsModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Import angular' FormGroup and FormBuilder classes

Next, open the src/app/app.component.ts file and import theFormGroup and FormBuilder classes as follows:

import { FormGroup, FormBuilder } from  '@angular/forms';

Create a form group and inject angular' FormBuilder

Next, define the contactForm variable which will be used to hold our form object (instance of FormGroup) and inject FormBuilder via the component constructor:

export class AppComponent  {

  contactForm: FormGroup;
  constructor(private formBuilder: FormBuilder) {
  }
}

Build the form with angular' FormBuilder

Next, define a createContactForm() method where we'll build our form:

  createContactForm(){
    this.contactForm = this.formBuilder.group({
      fullName: [''],  
      email: [''],
      message: ['']
    });
  }

We call the group() method of the injected instance of FormBuilder to create a FormGroup of three controls, fullName, email and message. Each control can take an optional array of options and validation rules.

Next, we call the method on the constructor:

constructor(private formBuilder:  FormBuilder)  {
   this.createContactForm();
}

Submit the angular 13 reactive form

Finally, add the following method, which will be called when our form is submitted:

  onSubmit() {
      console.log('Your form data : ', this.contactForm.value );
  }

Now, we need to bind this form object to our HTML form. Open the src/app/app.component.html file and add the following code:

<h1> Angular 13 reactive contact form example </h1>

<form [formGroup]="contactForm" (ngSubmit)="onSubmit()">
  <input type = "text" name = "fullName" placeholder = "Your full name" formControlName="fullName" >
  <br/>

  <input type = "email" name = "email" placeholder = "Your email" formControlName="email" >
  <br/>

  <textarea name = "message" placeholder = "Your message" formControlName="message" ></textarea>
  <br/>
  <input type = "submit" value = "Send">
</form> 

We use property binding to bind the form using the formGroup property. Next, we use formControlName to sync the FormControl objects in contactForm with the HTML form controls by name. See the docs for more details. Finally, we bind the ngSubmit event of the form to the onSubmit() method.

Here is the live example:

Conclusion

In this tutorial, we created an example contact form in angular 13 using both the template-based and reactive (model-based) approaches. We saw how to use the ngForm, ngSubmit, and ngModel directives to create a template-based form, as well as the FormGroup and FormBuilder classes to create a reactive form.



✋If you have any questions about this article, ask them in our GitHub Discussions 👈 community. You can also Gitter

✋ Want to master Angular 14? Read our angular tutorial and join our #DailyAngularChallenge where we learn to build components, directives, services, pipes and complete web, mobile, and desktop applications with latest Angular version.

✋ Make sure to join our Angular 14 Dev Community 👈 to discuss anything related to Angular development.

❤️ Like our page and subscribe to our feed for updates!