Sitemap
Donovan

Donovan

Learning. Putting up shots in React and Rails and anything else I get my hands on. Sights set on becoming an even more gainfully employed developer.

Using Template-Driven Forms in Angular

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.

component selector in root 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.

Create athlete component with object of type Athlete instantiated in the constructor with dummy data

Inside of create-athlete.component.html is where the form to create an athlete will be made. Let’s walk through each element of the form step by step:

The form tag has a template variable ‘#athleteForm’ set to ngForm to use at Form model level. The submit event is set to trigger our createAthlete() method with the athleteForm’s value passed as an object.

Get Donovan’s stories in your inbox

Join Medium for free to get updates from this writer.

The next div has class athlete-name and holds the input for an athlete’s name. The input field uses [(ngModel)] which gives two way data binding with our component. The component value set to [(ngModel)] will be updated with the value from the input and vice versa. If the value changes in our component it will also be updated in the html.

Press enter or click to view image in full size
Template Form in entirety

We have a form with two inputs, conditional elements based on input state, and a submit button. Each input has a ‘required’ validator, a name attribute, an instance of ngModel, and is bound to the respective component value.

The required validator will raise an error on our ngModel input which we can use to conditionally render an error message with a *ngIf directive.

The select element for the choice of teams is next to review. Since the selection is respective to the team variable in the component, use [(ngModel)] to bind. There is a first default option, then using the *ngFor directive iterate over list of teams and display each one with the team bound to [ngValue].

select element with teams from component

There is an input element of type checkbox that is bound with the confirmed value in the component. The submit button is disabled if confirmed has not been set to true.

Press enter or click to view image in full size
confirmed checkbox and submit button

Adding simple style elements to the css file can change class properties of the input based on if it is valid.

simple css for form

Now that there is a form set up, bound to values in our component; it is time to write a function that will handle the submission of the form, which we title createAthlete().

function createAthlete() will accept the incoming form data. Set the parameter to a data object accepting any type of object. Console log the data to see it raw and then check to see if the form updated the athlete by logging the athlete object.

createAthlete method receiving data from form

Opening the terminal and run the following command to view the form

ng serve - -o

Press enter or click to view image in full size
default form rendered

Since both inputs are required they will start off red and invalid. Upon entering text the inputs background color css property will change to green. The Create Athlete button will be disabled until the user clicks the box. There could be a condition put on this input as well to make sure the user fills the entire form out before confirming. At the bottom of the page the current athlete from the component is displayed showing that the component object is changing based on inputs from the form.

Press enter or click to view image in full size
valid form ready to create athlete

Once there is a valid form that is ready to be submitted click the Create Athlete button which will trigger the function in the component. This function console logged data in order to view data it was passed from the form sent by a user. The console will show that the data input from the user has made it to the component of the application.

Press enter or click to view image in full size
messages in our console sent from our createAthlete method in our create athlete component

Thinking ahead to further implementation of this function, it could be used to validate that a user has entered the right information in order to login, it can be used to create an instance of the Athlete class, or it could be used the same way to update. All of those depending on the logic to be implemented.

This demo showed how creating an angular application, creating a model class, creating a component to render a form, how to build the form and send data back to the component when form is submitted.

All code can be found on github. Always willing to help if I can. Good luck!

--

--

Donovan
Donovan

Written by Donovan

Learning. Putting up shots in React and Rails and anything else I get my hands on. Sights set on becoming an even more gainfully employed developer.