Build angular 17 forms with example

Build angular 17 forms with example

We'll learn how to design and use forms in Angular 17 by creating a basic contact form example.

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

Our online IDE will be https://stackblitz.com/. Simply create an account using your GitHub credentials, then choose one of the ready-made Angular templates to START A NEW APP. The most recent Angular 17 version will be the foundation of your Angular project.

Angular 17 and prior versions offer two methods for interacting with forms:

  • The template-based strategy;
  • The model-based strategy.

For minor tasks, there is no superior approach; choose the one that is most practical for you!

Create an angular 17 template-based form

Let's begin with the template-based approach by creating a simple angular 17 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 17 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 17 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 17 Form Example

This is the live project:

Create an angular 17 reactive form

After creating our angular 17 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 17 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 17 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, both the template-based and reactive (model-based) techniques were used to build an example contact form in angular 17. We learned how to design a template-based form using the ngForm, ngSubmit, and ngModel directives as well as a reactive form using the FormGroup and FormBuilder classes.



✋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!

Find a list of emojis to copy and paste