Angular Forms

Kevin O'Shaughnessy
8 min readJul 28, 2019

--

Welcome to this review of the Pluralsight course Angular Forms by Mark Zamoyta.

This is the third course on Pluralsight’s Angular learning path, following Angular The Big Picture, and Angular: Getting Started. It is a beginner friendly course and you do not necessarily need to watch those other courses to understand the material in this course.

The course is fairly short at 2 hours and 3 minutes. After a couple of brief introductory modules there are five main modules which I review here:

Form Basics in Angular

This begins with a look at Angular’s FormsModule and see how to import it into the AppModule.

Next we see how to create a Form Component, and we use Bootstrap for styling.

We add checkboxes, radio buttons, select control and options to our form. The end of the module looks at dates, colors and password controls.

At the end of this module we have a Bootstrap styled form which Angular is aware of, but Angular doesn’t yet know about the data content behind the controls.

Data Binding in Angular

This module starts with a look at NgForm, the directive that gives us access to all of Angular’s information about the form. We use it by setting a template reference variable like this:

<form #form=”ngForm”>

Here we are setting a variable to the literal string “ngForm”.

The next topic is NgModel. We also see that we can create our own data model, and in this course we use an interface.

Once we have our data model we use two way data binding to link up the model with the form:

[(ngModel)] = “variable”

The module ends we a lesson in copying form data. The do this by using the spread syntax to make a simple copy. Mark recommends using the Lodash utility library if you want to make a deep copy.

Form Validation

HTML5 Field validation

Angular works hand in hand with HTML5 form validation. In HTML5, form validation is mainly done with attributes on each field. Some examples are:

Mark shows us we can add the NgNativeValidate directive to the form tag, to allow the browser to use its own HTML5 validation. Because there are many differences between different browser’s implementations of validation, Angular suppresses this behavior by default.

We see examples of the above validation attributes in action. These are all behaviors that you don’t need Angular for.

CSS Classes for Validation

In this clip we start with ng-untouched and ng-touched. The ng-touched class is placed on a field when that field loses focus, e.g. when we click away from a textbox that we were typing into.

Another pair of opposites are ng-pristine and ng-dirty. Pristine means unmodified and dirty means modified.

Finally there is ng-valid and ng-invalid.

Mark uses interpolation to output the relevant CSS classes of a textbox control, in a demonstration of these CSS classes.

For further information see of the Control status CSS classes section of the Angular Form Validation guide.

NgModel properties for validation

For the six Angular CSS classes we’ve just covered, the NgModel property names are their equivalents without the ng- prefix. The ng-pristine class is associated with the pristine property, and so on.

In this clip we see how we can output the NgModel properties of our textbox control. These behave in the same kind of way we saw for the CSS classes.

Styling Forms with Validation Errors

In our CSS file we add a red border to any touched form controls that are invalid:

.ng-invalid:not(form).ng-touched {
border: 1px solid red;
}

It is important to note that you cannot have a space or a comma between the selectors.

We can also display an error message of our choice simply by updating our Angular html template. The following div is hidden if it is valid or untouched, and becomes visible when neither model properties are true:

<div [hidden]=”nameField.valid || nameField.untouched” class=”alert alert-danger”>Enter a name</div>

nameField needs to be defined as a template reference variable.

Submitting Forms

Some web designers and developers prefer for validation error messages to only show up once the user submits a form. We can implement this behavior using the ngSubmit event:

<form #form=”ngForm” (ngSubmit)=”onSubmit(form)”>

In our TypeScript file we create a basic onSubmit method:

onSubmit(form: NgForm) {
console.log(“in onSubmit:”, form.valid);
}

This is just for demonstration purposes can we can see if the form is valid using the developer tools. The method will be enhanced in a later module.

Mark also shows us how to create a new CSS class field-error and bind our textbox control to it using an expression:

<input id=”name” name=”name” class=”form-control” required #nameField=”ngModel” [(ngModel)]=”userSettings.name”
[class.field-error]=”form.submitted && nameField.invalid”>

Our textbox now shows the “Enter a name” error if we try to submit the form without a value for this required field.

Handling Form Control Events

This clip begins with the blur event, and how to execute code when this event fires. The following attributes are added to our input control:

(blur)=”onBlur(nameField)”

As we’re referencing a new function we need to define it in our TypeScript file:

onBlur(field: NgModel) {
console.log(“in onBlur:”, form.valid);
}

The module is concluded with a summary of what we’ve learned.

HTTP Form Posting and Data Access

Creating a Data Service

A data service will encapsulate our HTTP Access so that we avoid HTTP code littering our application. Using the Angular CLI:

> ng g s data

This creates a new data.service.ts file and a new testing spec file for us.

Form Posting Using Observables

If you are new to asynchronous programming in JavaScript, check out Reasoning about Asynchronous JavaScript.

You can use Promises in Angular, but in this clip we see how to use Observables instead, with the aid of the Reactive Extensions for JavaScript library, RxJS. We start by importing the Observable class into our data service:

import { Observable } from ‘rxjs’;

The we write a new method called postUserSettingsForm, and call it from our onSubmit method in user-settings-form.component.ts

This clip implements the plumbing code and gets us to the point where we can begin working with HttpClient.

HTTP Access Using HttpClient

HttpClient is a built-in Angular class for performing HTTP requests. We start by importing HttpClientModule into app.module.ts

import { HttpClientModule } from ‘@angular/common/http’;

We add HttpClientModule to our app module imports array, and then we go to our data service to update our postUserSettingsForm method. The url string is just a placeholder at the moment:

postUserSettingsForm(userSettings: UserSettings) : Observable<any> {
return this.http.post(‘url’, userSettings);
}

Posting a Form

There is a GitHub project written by Pablo Cantero which is called PutsReq. It lets us record HTTP requests and fake responses.

It’s very easy to use: click on the “Create a PutsReq” button to get a URL, then copy that URL into your program. Update the response builder to create your own fake responses.

We see an example of a simple fake response in this clip, and we get a successful response to our request.

Handling POST Errors

PutsReq is also useful for simulating error responses. Mark changes the response builder to:

response.status = 400;
response.body = { errorMessage: ‘some error goes here…’ };

This is the HTTP status code for Bad Request.

In our user-settings-form.component.ts we have a method called onHttpError and we handle the error here. We see how to display the error message on screen, with some Bootstrap alert styling.

Retrieving Data for Selecting Elements

We have a subscriptionType select element in our form with three subscription options (Monthly/Annual/Lifetime).

Instead of having these hardcoded into the template, we change the code to get these values from a data service.

<option *ngFor=”let type of subscriptionTypes | async”></option>

In our component TypeScript code we define a subscriptionTypes property with the type Observable<string[]>

In our onNgInit method, we call a new method in our data service called getSubscriptionTypes.

Third-party Form Controls

Form resources at angular.io

The Angular resources page has a UI Components section which we look at in this clip. At the time of writing there are 30 different options for your form controls. Angular Material has grown in popularity recently, and Mark introduces it here.

[For a one hour look at what the latest version of Angular Material has to offer, see ngConf ’19: Blast Off with Angular Material. Pluralsight has every talk from ngConf ’19 so even if you’re not interested in Angular Material there’s likely to be at least one talk of interest to you.]

Mark also introduces the Prime Faces UI library in this clip.

The rest of this module focuses on ngx-bootstrap.

Installing and using ngx-bootstrap

ngx-bootstrap is made by valor software and is based on the Bootstrap library which is originally from Twitter.

Mark begins by demonstrating the custom checkbox control. A nice feature of ngx-bootstrap is the ability to add a single control to our application (rather than needing to import the entire set). To add a package for the buttons component we type into our terminal:

ng add ngx-bootstrap — component buttons

Mark then shows us how to import the ButtonsModule into our application. This is also explained in valor software’s getting started guide.

At the end of this clip we have a button with text that changes from On and Off as we click on it.

Working with Buttons

We’ve been using the standard browser radio buttons throughout this course, but its time to give them a makeover.

See here for the ngx-bootstrap documentation on radio buttons.

In this clip we use the radio buttons to set the UI theme to light, medium or dark. We don’t see any visual change from clicking on the buttons, but we do see the value “light”, “medium” or “dark” posted along with the rest of the form data.

Dates and Date Ranges

ngx-bootstrap datepicker gives us a consistent look across all modern browsers. We start by importing BsDatepickerModule into our app.

As well as the date picker there is a date range picker. This is two calendars working together side by side to show a range of dates (or above and below if the browser width is narrow). It was written by Dan Grossman with contributions from over 100 other developers. It is available under the MIT license and the source code is available on GitHub.

Mark shows us how to use both the date picker and the date range picker.

Timepicker

The timepicker component is a lightweight & configurable timepicker directive.

In this clip we bind startTime to ngModel and see our new form control in action. The control has a number of additional features that aren’t demonstrated here, such as setting min and max times, and the setting seconds.

Rating Control

Rating controls are typically used to rate something from 1 star to 5 stars, but is customizable and we could for example rate up to 10 stars, and this is what Mark demonstrates here.

It is hard to say which is the best UI library for Angular because there are so many choices, but something to take away from this module is ngx-bootstrap is a pretty good library offering a lot of useful functionality.

This also wraps up this course from Mark Zamoyta. Thank you Mark for all the useful help and advice that you’ve given.

The final course in the beginner section of the Pluralsight Angular learning path is Angular CLI by John Papa, and I will be reviewing this next.

--

--

Kevin O'Shaughnessy

Sr. Full Stack Web Dev promoting better professional practices, tools, solutions & helping others.