Using Template-Driven Forms in Angular

Donovan
6 min readMar 2, 2022

Building small scale forms using Angular’s Forms Module

This demo is not aimed to make use of routing but is to show how one can create a form, bind to a component in order to have synchronized data that can be read and passed along. The steps are creating angular application, creating a model, creating a component to render a form, build form to submit new model instance.

Open a terminal, navigate to path, use the following angular command and make appropriate selections.

ng new <fileName>

Cd into this folder from terminal and use following command to open project in Visual Studio Code

code .

This demo will show how to use a template-driven form by making an Athlete model and a form to add a new athlete. The first step for using a template-driven form in Angular is to import FormsModule into the root module file, app.module.ts. Now the project has access to methods and configuration from Angular’s Forms module.

For the sake of encapsulation and maintaining a structure of code that can be scalable and easily maintained, we will create a model class for the type of object we wish to create. Use the following command to generate a class inside of a folder called, “model.”

ng generate class model/athlete

Inside of this class, Athlete, create a constructor that has the properties required to create an Athlete; name, sport, and team.

Model class Athlete with attributes in constructor

There will need to be a component responsible for displaying a form and saving and sending the data. Generate a new component with the following command

ng generate component create-athlete

Place this html selector in the app.component.html file.

Inside of the create-athlete component import the model, Athlete. This model will be used to model our form after, making sure the Athlete object being passed from the form fits the Athlete model we have defined in our project. In this component there is a list of teams defined for the select field, which will be shown shortly, an Athlete variable, initialized the Athlete variable with default data in our constructor.

Donovan

Learning. Puttin up shots in Angular and Java and Python and anything else I get my hands on. Sights set on becoming a gainfully employed developer.