DEV Community

Cover image for Building Forms The Angular Way
Eldrige
Eldrige

Posted on

Building Forms The Angular Way

Angular is a TypeScript-based open-source web application framework led by the Angular Team at Google and by a community of individuals and corporations.

Angular has two-main approaches to building forms. The Template Driven approach and the Reactive Form approach.

In this tutorial, we will be learning the template driven approach.

Recipe👨🍳

👉Import FormsModule into your main app.module component, and add it to the imports array.

appmodule

This will give us access to the following directives ngForm,ngModel and ngSubmit.

👉 Head over to your view

  • We will bind the ngSubmit event to a method in our logic.
  • Equally, we will create a template variable (#loginForm) and bind it to the ngForm directive, so as to hold a reference our form

Screenshot 2020-10-25 203154

-Behind the scenes, whenever a form element is created angular attributes the ngGroup directive to it automatically
-ngGroup is just an object that represents a collection of form-controls.
-Form controls are the smallest unit of a form, they hold the form values and the validation information.

-In your input make sure you gave a name property, and attach the ngModel directive to it
Attaching the ngModel directive gives us one-way binding, and attributes a form-control to our input

ngModel

-Finally, add a button with the type submit

👉 Head over to your logic and add the method, that will log the values entered into the form

TDD logic

Now, Open your form in the browser, and fill in the form.

Browser

After submitting the form, check your console. You will see the values you just submitted

output

Congratulations!!!🎉🍾㊗🎊 You just created your first angular form. In the upcoming tutorials, we will discover how to create forms, using the reactive approach.

Top comments (4)

Collapse
 
abdurrkhalid333 profile image
Abdur Rehman Khalid

That's a pretty nice article to share your learning of Angular Forms, there is a suggestion for you, try to use the FormControl next time. You will be happier :)

Collapse
 
jwp profile image
John Peters • Edited

Ngmodel has a Form control. dev.to/jwp/angular-ngmodel-model-a...

Collapse
 
jwp profile image
John Peters

Nice glad to see you are using ngmodel!

Collapse
 
traore19 profile image
traore19

nice