Build angular 17 forms with example (2024)

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:

Build angular 17 forms with example (1)

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.

  • Date:

Build angular 17 forms with example (2024)
Top Articles
SUMMER OF FIRSTS: ROYAL CARIBBEAN ALL IN ON 2023 SEASONAL CARIBBEAN CRUISES
ROYAL CARIBBEAN OPENS EPIC LINEUP OF EUROPEAN ADVENTURES FOR SUMMER 2023
Spasa Parish
Rentals for rent in Maastricht
159R Bus Schedule Pdf
Sallisaw Bin Store
Black Adam Showtimes Near Maya Cinemas Delano
Espn Transfer Portal Basketball
Pollen Levels Richmond
11 Best Sites Like The Chive For Funny Pictures and Memes
Things to do in Wichita Falls on weekends 12-15 September
Craigslist Pets Huntsville Alabama
Paulette Goddard | American Actress, Modern Times, Charlie Chaplin
Red Dead Redemption 2 Legendary Fish Locations Guide (“A Fisher of Fish”)
What's the Difference Between Halal and Haram Meat & Food?
R/Skinwalker
Rugged Gentleman Barber Shop Martinsburg Wv
Jennifer Lenzini Leaving Ktiv
Justified - Streams, Episodenguide und News zur Serie
Epay. Medstarhealth.org
Olde Kegg Bar & Grill Portage Menu
Cubilabras
Half Inning In Which The Home Team Bats Crossword
Amazing Lash Bay Colony
Juego Friv Poki
Dirt Devil Ud70181 Parts Diagram
Truist Bank Open Saturday
Water Leaks in Your Car When It Rains? Common Causes & Fixes
What’s Closing at Disney World? A Complete Guide
New from Simply So Good - Cherry Apricot Slab Pie
Drys Pharmacy
Ohio State Football Wiki
Find Words Containing Specific Letters | WordFinder®
FirstLight Power to Acquire Leading Canadian Renewable Operator and Developer Hydromega Services Inc. - FirstLight
Webmail.unt.edu
2024-25 ITH Season Preview: USC Trojans
Metro By T Mobile Sign In
Restored Republic December 1 2022
12 30 Pacific Time
Free Stuff Craigslist Roanoke Va
Wi Dept Of Regulation & Licensing
Pick N Pull Near Me [Locator Map + Guide + FAQ]
Crystal Westbrooks Nipple
Ice Hockey Dboard
Über 60 Prozent Rabatt auf E-Bikes: Aldi reduziert sämtliche Pedelecs stark im Preis - nur noch für kurze Zeit
Wie blocke ich einen Bot aus Boardman/USA - sellerforum.de
Infinity Pool Showtimes Near Maya Cinemas Bakersfield
Dermpathdiagnostics Com Pay Invoice
How To Use Price Chopper Points At Quiktrip
Maria Butina Bikini
Busted Newspaper Zapata Tx
Latest Posts
Article information

Author: Nathanial Hackett

Last Updated:

Views: 6446

Rating: 4.1 / 5 (72 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Nathanial Hackett

Birthday: 1997-10-09

Address: Apt. 935 264 Abshire Canyon, South Nerissachester, NM 01800

Phone: +9752624861224

Job: Forward Technology Assistant

Hobby: Listening to music, Shopping, Vacation, Baton twirling, Flower arranging, Blacksmithing, Do it yourself

Introduction: My name is Nathanial Hackett, I am a lovely, curious, smiling, lively, thoughtful, courageous, lively person who loves writing and wants to share my knowledge and understanding with you.