Google+
4elements web design & consultancy

4elements

Blog

  • 18

    Introduction to Forms in Angular 4: Template-Driven Forms

    4elements | web design The Hague blog • Introduction to Forms in Angular 4: Template-Driven Forms

    Final product image
    What You'll Be Creating

    Forms are critical to any modern front-end application, and they're a feature that we use every day, even if don't realize it. Forms are required for securely logging in a user to the app, searching for all the available hotels in a particular city, booking a cab, building a to-do list, and doing tons of other things that we are used to. Some forms have just a couple of input fields, whereas other forms could have an array of fields that stretch to a couple of pages or tabs. 

    In this tutorial, we will be talking about different strategies available for developing forms in Angular. Irrespective of the strategy that you choose, here are the things that a form library should cover:

    • Support two-way binding so that the input control values are in sync with the component state.
    • Keep track of the form state and use visual cues to let the user know whether the current state is valid or not. For instance, if the username has invalid characters, a red border should appear around the input field for the username.
    • Have a mechanism to display validation errors properly.
    • Enable or disable certain parts of the form unless some validation criteria are met.

    Introduction to Forms in Angular

    Angular, being a full-fledged front-end framework, has its own set of libraries for building complex forms. The latest version of Angular has two powerful form-building strategies. They are:

    • template-driven forms 
    • model-driven or reactive forms

    Both the technologies belong to the @angular/forms library and are based on the same form control classes. However, they differ remarkably in their philosophy, programming style, and technique. Choosing one over the other depends on your personal taste and also on the complexity of the form that you are trying to create. In my opinion, you should try both the approaches first and then choose one that fits your style and the project at hand. 

    The first part of the tutorial will cover template-driven forms with a practical example: building a signup form with validation for all form fields. In the second part of this tutorial, we will retrace the steps to create the same form using a model-driven approach instead. 

    Template-Driven Forms

    The template-driven approach is a strategy that was borrowed from the AngularJS era. In my opinion, it is the most straightforward method for building forms. How does it work? We will be using some Angular directives. 

    Directives allow you to attach behavior to elements in the DOM.
    — Angular Documentation

    Angular provides form-specific directives that you can use to bind the form input data and the model. The form-specific directives add extra functionality and behavior to a plain HTML form. The end result is that the template takes care of binding values with the model and form validation. 

    In this tutorial, we will be using template-driven forms to create the signup page of an application. The form will cover the most common form elements and different validation checks on these form elements. Here are the steps that you will follow in this tutorial.

    • Add FormsModule to app.module.ts.
    • Create a class for the User model.
    • Create initial components and layout for the signup form.
    • Use Angular form directives like ngModelngModelGroup, and ngForm.
    • Add validation using built-in validators.
    • Display validation errors meaningfully.
    • Handle form submission using ngSubmit.

    Let's get started.

    Prerequisites

    The code for this project is available on my GitHub repo. Download the zip or clone the repo to see it in action. If you prefer to start from scratch instead, make sure that you have Angular CLI installed. Use the ng command to generate a new project. 

    Next, generate a new component for the SignupForm.

    Replace the contents of app.component.html with this:

    Here is the directory structure for the src/ directory. I've removed some non-essential files to keep things simple.

    As you can see, a directory for the SignupForm component has been created automatically. That's where most of our code will go. I've also created a new User.ts for storing our User model.

    The HTML Template

    Before we dive into the actual component template, we need to have an abstract idea of what we are building. So here is the form structure that I have in my mind. The signup form will have several input fields, a select element, and a checkbox element. 

    The HTML Template

    Here is the HTML template that we will be using for our registration page. 

    HTML Template

    The CSS classes used in the HTML template are part of the Bootstrap library used for making things pretty. Since this is a not a design tutorial, I won't be talking much about the CSS aspects of the form unless necessary. 

    Basic Form Setup

    To use the template-driven form directives, we need to import the FormsModule from @angular/forms and add it to the imports array in app.module.ts.

    app/app.module.ts

    Next, create a class that will hold all properties of the User entity. We can either use an interface and implement it in the component or use a TypeScript class for the model.

    app/User.ts

    Now, create an instance of the class in the SignupForm component. I've also declared an additional property for the gender. 

    app/signup-form/signup-form.component.ts

    For the signup-form.component.html file, I am going to use the same HTML template discussed above, but with minor changes. The signup form has a select field with a list of options. Although that works, we will do it the Angular way by looping through the list using the ngFor directive.

    app/signup-form/signup-form.component.html

    Next, we want to bind the form data to the user class object so that when you enter the signup data into the form, a new User object is created that temporarily stores that data. This way, you can keep the view in sync with the model, and this is called binding. 

    There are a couple of ways to make this happen. Let me first introduce you to ngModel and ngForm.

    ngForm and ngModel

    ngForm and ngModel are Angular directives that are essential to creating template-driven forms. Let's start with ngForm first. Here is an excerpt about ngForm from the Angular docs.

    The NgForm directive supplements the form element with additional features. It holds the controls you created for the elements with an ngModel directive and name attribute, and monitors their properties, including their validity. It also has its own valid property which is true only if every contained control is valid.

    First, update the form with the ngForm directive:

    app/signup-form/signup-form.component.html

    #signupForm is a template reference variable that refers to the ngForm directive which governs the entire form. The example below demonstrates the use of a ngForm reference object for validation.

    app/signup-form/signup-form.component.html

    Here, signupForm.form.valid will return false unless all the form elements pass their respective validation checks. The submit button will be disabled until the form is valid.  

    As for binding the template and the model, there are plenty of ways to do this, and ngModel has three different syntaxes to tackle this situation. They are:

    1. [(ngModel)] 
    2. [ngModel]
    3. ngModel

    Let's start with the first one.

    Two-Way Binding Using [(ngModel)]

    [(ngModel)] performs two-way binding for reading and writing input control values. If a [(ngModel)] directive is used, the input field takes an initial value from the bound component class and updates it back whenever any change to the input control value is detected (on keystroke and button press). The image below describes the two-way binding process better.

    Two-way binding with ngModel

    Here is the code for the email input field:

    [(ngModel)] = "user.email" binds the user's email property to the input value. I've also added a name attribute and set name="email". This is important, and you will get an error if you've not declared a name attribute while using ngModel. 

    Similarly, add a [(ngModel)] and a unique name attribute to each form element. Your form should look something like this now:

    app/signup-form/signup-form.component.html

    The ngModelGroup is used to group together similar form fields so that we can run validations only on those form fields. Since both the password fields are related, we will put them under a single ngModelGroup. If everything is working as expected, the component-bound user property should be in charge of storing all the form control values. To see this in action, add the following after the form tag:

    Pipe the user property through the JsonPipe to render the model as JSON in the browser. This is helpful for debugging and logging. You should see a JSON output like this. 

    An example of JSON output

    The values are flowing in from the view to the model. What about the other way around? Try initializing the user object with some values.

    app/signup-form/signup-form.component.ts

    And they automatically appear in the view:

    The two-way binding [(ngModel)] syntax helps you build forms effortlessly. However, it has certain drawbacks; hence, there is an alternate approach that uses ngModel or [ngModel].

    Adding ngModel to the Mix

    When ngModel is used, we are in fact responsible for updating the component property with the input control values and vice versa. The input data doesn't automatically flow into the component's user property.

    So replace all instances of [(ngModel)] = " " with ngModel. We will keep the name attribute because all three versions of ngModel need the name attribute to work. 

    app/signup-form/signup-form.component.html

    With ngModel, the value of the name attribute will become a key of the ngForm reference object signupForm that we created earlier. So, for example, signupForm.value.email will store the control value for the email id. 

    Replace {{user | json}} with {{signupForm.value | json }} because that's where all the state is stored right now. 

    One-Way Binding Using [ngModel]

    What if you need to set the initial state from the bound class component? That's what the [ngModel] does for you. 

    One-way binding with ngModel

    Here the data flows from the model to the view. Make the following changes to the syntax to use one-way binding:

    app/signup-form/signup-form.component.html

    So which approach should you choose? If you're using [(ngModel)] and ngForm together, you will eventually have two states to maintain—user and signupForm.value—and that could be potentially confusing. 

    Hence, I will recommend using the one-way binding method instead. But that's something for you to decide.

    Validation and Displaying Error Messages 

    Here are our requirements for the validation.

    • All form controls are required.
    • Disable the submit button until all input fields are filled.
    • The email field should strictly contain an email id.
    • The password field should have a minimum length of 8.
    • Both the password and confirmation should match.
    Form with Validation using Template-driven forms
    Our form with validation in place

    The first one is easy. You have to add a required validation attribute to each form element like this:

    app/signup-form/signup-form.component.html

    Apart from the required attribute, I've also exported a new #email template reference variable. This is so that you can access the input box's Angular control from within the template itself. We will use it to display errors and warnings. Now use the button's disabled property to disable the button:

    app/signup-form/signup-form.component.html

    To add a constraint on email, use the pattern attribute that works with input fields. Patterns are used to specify regular expressions like the one below:

    For the password field, all you have to do is add a minlength=" " attribute:

    app/signup-form/signup-form.component.html

    To display the errors, I am going to use the conditional directive ngIf on a div element. Let's start with the input control field for email:

    app/signup-form/signup-form.component.html

    There is a lot going on here. Let's start with the first line of the error section.

    Remember the #email variable that we exported earlier? It carries some amount of information about the input control state of the email field. This includes: email.valid, email.invalid, email.dirty, email.pristine, email.touched, email.untouched, and email.errors.  The image below describes each of those properties in detail.

    Different class properties for displaying errors

    So the div element with the *ngIf will be rendered only if the email is invalid. However, the user will be greeted with errors about the input fields being blank even before they have a chance to edit the form. 

    To avoid this scenario, we've added the second condition. The error will be displayed only after the control has been visited or the control's value has been changed.

    The nested div elements are used to cover all the cases of validation errors. We use email.errors to check all possible validation errors and then display them back to the user in the form of custom messages. Now, follow the same procedure for the other form elements. Here is how I've coded the validation for the passwords. 

    app/signup-form/signup-form.component.html

    This is starting to look a bit messy. Angular has a limited set of validator attributes: required, minlength, maxlength, and pattern. To cover any other scenario like that of password comparison, you will have to rely on nested ngIf conditionals as I did above. Or ideally, create a custom validator function, which I will cover in the third part of this series.

    In the code above, I've used the ngIf else syntax which was introduced in the latest version of Angular. Here is how it works:

    Submit the Form Using ngSubmit

    We have nearly finished the form. Now we need to be able to submit the form, and the control of the form data should be handed over to a component method, say onFormSubmit().

    app/signup-form/signup-form.component.ts

    Now, for the component:

    app/signup-form/signup-form.component.ts

    Final Demo

    Here is the final version of the application. I've added a few bootstrap classes to make the form pretty.

    Summary

    We're all done here. In this tutorial, we covered everything that you need to know about creating a form in Angular using the template-driven approach. Template-driven forms are popular for their simplicity and ease of use. 

    However, if you need to build a form with lots of form elements, this approach will become messy. So, in the next tutorial, we will cover the model-driven way of building the same form. 

    Share your thoughts in the comments below.

    martijn broeders

    founder/ strategic creative at 4elements web design & consultancy
    e-mail: .(JavaScript must be enabled to view this email address)
    phone: 06 38 55 28 54

By - category

    By - date