In the last article, we’ve learned about Template driven forms. And here, we’ll look into a different approach to create forms and that is Reactive forms. And this approach gives us more control over the structure and the behavior of our form. If you want to build dynamic forms where input fields are rendered based on some data structure that you get from the server, then the only option is to create this controller objects in the code. And by the way, Reactive forms are easier to unit test. So by the end of this article, we’ll be able to:
- Create Control objects programmatically
- Add validation to the form
- Implement custom validation
- Implement asynchronous validation (that involves contacting the server)
- Build forms that include an array of objects that are added or removed dynamically.
But if you’re a beginner in Angular and you want to start your journey with Angular then here is the roadmap for you.
- Introduction And Setting Up The Environment - Part One
- Typescript in a Nutshell - Part Two
- Building Blocks of Angular - Part Three
- Binding Variations And Displaying Data - Part Four
- Building Reusable Components – Part Five
- Directives – Part Six
- Template Driven Form – Part Seven
And it is the 8th article of Angular series. So let’s start our journey with Angular.
Building a Bootstrap Form
To speed things up, I’ve built the form for you. Just extract the RAR file and copy paste the component into your project component folder. And then register this component in app.module.ts and call the component with its selector in app.component.html.

So this is our signup-form.
Creating Controls Programmatically
It is the simple bootstrap form and now we want to convert it to the Angular Reactive form. You already know that in the template driven form, we use ngModel directive on input elements and this directive internally creates an instance of FormControl. But now when we’re building the reactive form, we should create this FormControl object explicitly in the code. So let’s go to our signup-form.component.ts and here we’ll import a couple of classes.
- import { FormGroup, FormControl } from "@angular/forms";
Next, we need to create an instance of FormGroup, So,

Now if you see this image, we have 3 overloaded constructors of FormGroup. Second and third are optional but the 1st is necessary. It is the object property containing one or more key value pairs, each key is a string and the value is an AbstractControl
Now what is AbstractControl?
Well in OOP, we’ve this concept called inheritance. So if we have multiple classes that have some common behavior and properties, instead of implementing this common behavior in multiple places we define them once in a parent or base class and then those other classes inherit this common behavior from their base class. So in Angular, AbstractControl is the base class and FormControl and FormGroup are child classes. All the properties which you see common in FormControl and FormGroup classes are actually defined in AbstractControl class

So back in component and as the intellisense suggests.
- export class SignupFormComponent {
- form = new FormGroup({
- username: new FormControl()
- });
- }
And if you’re dealing with a complex form that includes sub groups then you’ll create the instance of FormGroup here instead of FormControl with username. And then this FormGroup contains 1 or more FormControl objects. Let’s come back to the point,
- export class SignupFormComponent {
- form = new FormGroup({
- username: new FormControl(),
- password: new FormControl()
- });
- }
So this is how we explicitly create FormGroup and FormControl objects in the code. Now you might think that it is the javascript object initializer syntax and here we use the key in string. Yes we can go with string syntax as well, it is valid but if it is a single keyword like here we have username. It is ok if we implement it without single quotes.
Now we need to go to our template and associate our input fields with this FormControl objects. So here back in form template, first we need to apply a directive of our form element.
- <form [formGroup]="form">
- </form>
Here ‘form’ is the component property which we created just above and [formGroup] is because of new FormGroup() as we’re creating the FormGroup instance in form field. Now inside this group, we’ve 2 controls (username and password). Now let’s define these properties in our template with the help of formControName attribute
- <form [formGroup]="form">
- <div class="form-group">
- <label for="username">Username</label>
- <input
- formControlName="username"
- id="username"
- type="text"
- class="form-control">
- </div>
- <div class="form-group">
- <label for="password">Password</label>
- <input
- formControlName="password"
- id="password"
- type="text"
- class="form-control">
- </div>
- <button class="btn btn-primary" type="submit">Sign Up</button>
- </form>
Now save the files and open it into the browser.

Now, if you open angular.io and search for formgroupdirective, you’ll see that this directive is defined in ReactiveFormsModule so all the directives for building reactive forms are defined in a separate module called ReactiveFormsModule.

So we need to explicitly import into our main module. So let’s go to the app.module.ts
- imports: [
- BrowserModule,
- FormsModule,
- ReactiveFormsModule
- ],
And of course, our auto import plugin automatically adds the import statement on the top.
- import { FormsModule, ReactiveFormsModule } from "@angular/forms";
Now if you go back to the browser you’ll see no error message in the console now. Everything is working perfectly.

Adding Validation
Now let’s add the validation to this form. In the previous article, when we were building template driven forms we were using html5 attributes. But here when we’re building reactive forms we’ll not use these html5 attributes. We assign validators when we’re creating FormControl object.

First argument is the initial state and the 2nd argument is validator object and its type is ValidatorFn or ValidatorFn[]
So what is ValidatorFn?
In Angular, we’ve a class called Validators. So all the Validators we have in our template driven forms, and they exist here as well. These validators or methods defined in this class. So here we’ve different methods,
- Validators.required()
- Validators.minlength()
- Validators.maxlength()
- Validators.pattern()
- Validators.email()
And obviously, all of these methods are static. So we can access them with the class name.
username: new FormControl('', Validators.required)
Note I’m not calling required() here, we’re simply passing the reference to the constructor function because the 2nd argument for the constructor of FormControl requires validatorFn which is basically a function reference
- export class SignupFormComponent {
- form = new FormGroup({
- username: new FormControl('', Validators.required),
- password: new FormControl('', Validators.required)
- });
- }
Now we want to add the valdation messages. We already know that we can access the component fields directly in the component html files.
- <div class="form-group">
- <label for="username">Username</label>
- <input
- formControlName="username"
- id="username"
- type="text"
- class="form-control">
- <div *ngIf="form" class="alert alert-danger">
- Username is Required.
- </div>
- </div>
Now form is the instance of FormGroup class and here we’ve the method called get() and from here we can get access to any FormControl object inside this group. So,
- <div *ngIf="form.get('username').touched && form.get('username').invalid" class="alert alert-danger">
- Username is Required.
- </div>
Now let’s see in the browser if our code is working properly,

Now our code is little bit noisy and we need to cleanup this code. So come back to the component and here we can define the property that gives us access to this username FormControl object. So remember properties, they look like fields from the outside but internally they are methods actually. So here we define getter to call the username()
- export class SignupFormComponent {
- form = new FormGroup({
- username: new FormControl('', Validators.required),
- password: new FormControl('', Validators.required)
- });
- get username() {
- return this.form.get('username');
- }
- }
And now in signup-form.component.html
- <form [formGroup]="form">
- <div class="form-group">
- <label for="username">Username</label>
- <input
- formControlName="username"
- id="username"
- type="text"
- class="form-control">
- <div *ngIf="username.touched && username.invalid" class="alert alert-danger">
- Username is Required.
- </div>
- </div>
- <div class="form-group">
- <label for="password">Password</label>
- <input
- formControlName="password"
- id="password"
- type="text"
- class="form-control">
- </div>
- <button class="btn btn-primary" type="submit">Sign Up</button>
- </form>
This is the final code. And if you run the application in the browser, it is working fine.
Different Validation Errors
Now let’s see how to add multiple validators and how to show the different validation error messages in the browser.
- export class SignupFormComponent {
- form = new FormGroup({
- username: new FormControl('', [
- Validators.required,
- Validators.minLength(3)
- ]),
- password: new FormControl('', Validators.required)
- });
- get username() {
- return this.form.get('username');
- }
- }
Now let’s display specific error messages.
- <div *ngIf="username.touched && username.invalid" class="alert alert-danger">
- <div *ngIf="username.errors.required">Username is Required.</div>
- <div *ngIf="username.errors.minlength">Username should be minimum {{ username.errors.minlength.requiredLength }} characters.</div>
- </div>
Now let’s test the application. And yes it is working fine.
Implementing Custom Validation
Let’s see how to implement custom validator function. Now come on to the Angular documentation and search for validatorFn. It is an interface as it is indicated with I in search. And if we read the documentation of this function we’ll see that in this interface functions represents with this signature.

Function that takes AbstractControl as parameter and returns ValidationErrors or null. In the Typescript article, we learned that we use interfaces defined a Shape or object. We can use interfaces to define the shape of function as well. Any function that matches above signature is considered a ValidatorFn. We can define this function anywhere in our application but it is better to put all the ValidatorFn inside a class. This way we can encapsulate them in a single place.
So back in VS Code, We add a new file ‘username.validators.ts’ in signup-form folder. Here we export a class and define the functions which functionality we want.
- import { AbstractControl, ValidationErrors } from "@angular/forms";
- export class UsernameValidators {
- cannotContainSpace(control: AbstractControl) : ValidationErrors | null {
- if ((control.value as string).indexOf(' ') >= 0) {
- // We should return Validation Errors
- }
- }
- }
Now back again to the Angular documentation and search for ValidationErrors

And here we see, this ValidationErrors represent an object that has one or more key value pairs, keys are string and values can be anything. So in our case,
- if ((control.value as string).indexOf(' ') >= 0) {
- return { cannotContainSpace}
- }
And for another scenario, if we are going to implement that built in required validator, the key here would be required.
- if ((control.value as string).indexOf(' ') >= 0) {
- return { required }
- }
To come back to the point; so the value can be anything, if we want to supply some details to the user then we need to add an object here otherwise we can add simple type like true here.
- if ((control.value as string).indexOf(' ') >= 0) {
- return { cannotContainSpace: true };
- }
And as for another example, if we’re going to build the built-in minLength validator, our object here will be like this,
- if ((control.value as string).indexOf(' ') >= 0) {
- return { minlength: {
- requiredLength: 10,
- actualLength: control.value.length
- }};
- }
So if you want to provide details to the client, you use a complex object as a value here. Now let’s undo this, and come back to the cannotContainSpace. So if the validation fails, we return the validationerrors object or null.
- export class UsernameValidators {
- cannotContainSpace(control: AbstractControl) : ValidationErrors | null {
- if ((control.value as string).indexOf(' ') >= 0) {
- return { cannotContainSpace: true };
- }
- return null;
- }
- }
One last step, in order to access this cannotContainSpace() method to the outside without having to create an instance of the class, we decorate this method with static.
- import { AbstractControl, ValidationErrors } from "@angular/forms";
- export class UsernameValidators {
- static cannotContainSpace(control: AbstractControl) : ValidationErrors | null {
- if ((control.value as string).indexOf(' ') >= 0) {
- return { cannotContainSpace: true };
- }
- return null;
- }
- }
So here we have customValidator, now we need to import it into our component. Now let’s consume it in the component.
- form = new FormGroup({
- username: new FormControl('', [
- Validators.required,
- Validators.minLength(3),
- UsernameValidators.cannotContainSpace
- ]),
- password: new FormControl('', Validators.required)
- });
Before going any further, we just emphasize that in this demo I put this custom validator inside signup-form folder because this is the only place we’re using this validator. In a large complex applications, chances are you might have different components that use the same validator. If that’s the case you need to put all these validators in a common place. For example, add a folder ‘common’ in ‘app’ folder and inside we can place validators.

Now let’s define the validation message for this custom validator.
- <div *ngIf="username.touched && username.invalid" class="alert alert-danger">
- <div *ngIf="username.errors.required">Username is Required.</div>
- <div *ngIf="username.errors.minlength">Username should be minimum {{ username.errors.minlength.requiredLength }} characters.</div>
- <div *ngIf="username.errors.cannotContainSpace">Username cannot contain space.</div>
- </div>
Here cannotContainSpace is the key which we defined in the return statement here.
- if ((control.value as string).indexOf(' ') >= 0) {
- return { cannotContainSpace: true };
- }
Now let’s try this validation in the browser.

Asynchronous Operations
Sometimes we need to call the server to validate a given value. For example here we want to call the server to see if this username is taken or not. So let’s go and implement the custom validator. So back in the UsernameValidators class and here we’ll add another static method.
- static shouldBeUnique(control: AbstractControl) : ValidationErrors | null {
- }
Now to implement this method, we don’t want to call to server yet because we’ve not covered the http services yet and how we connect through http services in Angular. So let’s make it simple and simulate a call to the server.
- static shouldBeUnique(control: AbstractControl) : ValidationErrors | null {
- if (control.value === 'usama')
- return { shouldBeUnique: true };
- return null;
- }
So the username is usama, we assume it is taken otherwise the username is unique. And it is really very simple implementation.
What should we do to simulate the call to the server? Well calling the server is what we classify as an Asynchronous Operation. What is an Asynchronous Operation? When we call the server there is going to be little bit of a delay in I/O operations. That delay may be half a second or of 3 seconds or it may be 20 seconds depending upon the connection speed. In situations like that the process that is executing our code doesn’t want to block while waiting for the result coming back from the server. Because if that process blocks, user can’t interact with the browser. So that process is going to call that server behind the scenes and when the result is ready, it's going to display to the user. So this is what we call asynchronous operation. Asynchronous means none blocking (multiple tasks at a time).
Calling the server is not the only asynchronous operation in Javascript. Another example of asynchronous operation is the timeout function that you have probably seen before.
- setTimeout(() => {
- console.log('ok');
- }, 2000);
We can use this to simulate the call to the server. setTimeout() has callback function inside and we know that we can use the arrow functions here if callback function has no parameters. We already discussed it in our Typescript article. Now let’s move the code inside the callback function.
- static shouldBeUnique(control: AbstractControl) : ValidationErrors | null {
- setTimeout(() => {
- if (control.value === 'usama')
- return { shouldBeUnique: true };
- return null;
- }, 2000);
- }
setTimeout() is an asynchronous function which we can simulate this to the call to the server. It will be executed after 2k milliseconds and we don’t want to be blocked while waiting for 2 seconds.
The issue we’ve here in this code, return statement inside setTimeout() is not returning to the shouldBeUnique() function. They are just returning from the callback function that we pass to the setTimeout() function. Here we’re just simply calling setTimeout() function. If you want to get rid off this compilation error, we need to return something on the same scope of setTimeout() function.
- static shouldBeUnique(control: AbstractControl) : ValidationErrors | null {
- setTimeout(() => {
- if (control.value === 'usama')
- return { shouldBeUnique: true };
- return null;
- }, 2000);
- return null;
- }
Now the compilation error is gone. However we can’t use this validator function inside our component because this function will always return null which means no error. So the issue we’ve here we’re dealing with asynchronous operation. When we’re building validator, it involves asynchronous operation and we need to use a different signature for our validator function.
Asynchronous Validations
Back in our component, here we create the FormControl object.
- form = new FormGroup({
- username: new FormControl('', Validators.required),
- password: new FormControl('', Validators.required)
- });
So far we’ve seen these 2 parameters. The 1st one is the initial value and the 2nd one is more or more validator function. Now let’s take a look at the 3rd parameter. Here we’ve async validator,

And as you can see the type of the parameter is either AsyncValidatorFn or an array of AsyncValidatorFn. Let’s go back to Angular website and look at the declaration of this interface.

Now look at the signature of this function. Just like before this validator function takes parameter of type AbstractControl but the return type is a little bit different. Previously the return type was ValdiationErrors object or null. Now it is the promise of ValidationErrors or Observable of ValidationErrors or null. So basically this function should either return a promise or observable.
What are these classes (promise, observable)
In javascript, we use promises and observables to work with asynchronous operations. And here we discuss the promise, we’ll see observable later. We want our validator function to return promise of validation errors or null. First of all, study Promise in Javascript to get an idea about Promise.
So now let’s go back and modify our validator function to return a promise.
- static shouldBeUnique(control: AbstractControl) : Promise<ValidationErrors | null> {
- return new Promise()
- setTimeout(() => {
- if (control.value === 'usama')
- return { shouldBeUnique: true };
- return null;
- }, 2000);
- return null;
- }
Now when we create the Promise object, here is the screenshot of constructor.

Now the complex thing has started, it is quite difficult to understand this concept. It's too complicated. Let’s try to understand.

The reason it looks complicated is because of error function syntax. And here we’ve 3 error functions and we’ll simplify them one by one.
Look at the first one here,
- (value?: T | PromiseLike<T>) => void
This error function represents function with this parameter.
- (value? : T | PromiseLike<T>)
Which is either a value which might be optional or another Promise. So this function takes parameter and returns void. And all this is the parameter of resolve parameter here. Let’s simplify this and get rid of this error function syntax. Just remember,
- resolve: (value?: T | PromiseLike<T>) => void
resolve is a function that takes a value and returns void.
Now look at the 2nd error function,
- (reason? : any) => void
This function takes parameter called reason which is optional and the type of this parameter is any. And as you can see this function returns void. And once again,
- reject: (reason? : any) => void
this function is the type of reject parameter here. So let’s simplify this once again, but keep in mind reject is a function that takes an optional parameter called reason and returns void.
Now we’ve another error function
- executor: (resolve, reject) => void
the function that takes 2 parameters (resolve and reject). And both these parameters are functions. So this function takes these 2 parameters and returns void. And this function is the type of executor which is the parameter of constructor of the Promise class.
Now back again in code and here we need to apply 2 parameters resolve and reject
- return new Promise((resolve, reject))
One important thing is when you’re using resolve and reject here. Don’t import any statement. We’ve only 1 import statement here,
- import { AbstractControl, ValidationErrors } from "@angular/forms";
So be aware. Otherwise you’ll see the error while using resolve and reject in your coode.
Now we know that both these parameters are functions. So this goes to code block. And this arrow function is the void function, we already know. We use resolve parameter to return a value with the consumer of this Promise so whoever is interested in this Promise when our asynchronous function completes, we want to give them some value. We use this resolve function to return a value. So instead of return true, we call resolve(true)
- static shouldBeUnique(control: AbstractControl) : Promise<ValidationErrors | null> {
- return new Promise((resolve, reject) => {
- resolve(true);
- });
- setTimeout(() => {
- if (control.value === 'usama')
- return { shouldBeUnique: true };
- return null;
- }, 2000);
- return null;
- }
And in case of failure, we’re gonna use reject parameter. And in reject, we can optionally specify the reason of failure.
- return new Promise((resolve, reject) => {
- reject('error');
- });
And if it is the complex object with details then we can create the object inside reject().
So now that we have the promise object and now we move the setTimeout() code into the body of executor function.
- static shouldBeUnique(control: AbstractControl) : Promise<ValidationErrors | null> {
- return new Promise((resolve, reject) => {
- setTimeout(() => {
- if (control.value === 'usama')
- return { shouldBeUnique: true };
- return null;
- }, 2000);
- });
- // Remember: it is for demo purpose, it is actually not part of real implementation.
- return null;
- }
So now here we have the asynchronous operation when this operation completes, you want to return the value, the consumer of this promise. So instead of returning ValidationErrors object here, we're going to call resolve and give the object into it.
- if (control.value === 'usama')
- resolve({ shouldBeUnique: true });
And similarly instead of returning null, we use resolve(null)
- static shouldBeUnique(control: AbstractControl) : Promise<ValidationErrors | null> {
- return new Promise((resolve, reject) => {
- setTimeout(() => {
- if (control.value === 'usama')
- resolve({ shouldBeUnique: true });
- else
- resolve(null);
- }, 2000);
- });
- }
So this is how we implement an async validator. We can use these parameters (resolve and reject) and either return some value to the consumer of this promise or return an error. Now finally we need to register this in our FormControl object,
- export class SignupFormComponent {
- form = new FormGroup({
- username: new FormControl('',
- Validators.required,
- UsernameValidators.shouldBeUnique),
- password: new FormControl('', Validators.required)
- });
- get username() {
- return this.form.get('username');
- }
- }
Now to display this validation error, we should go to our template and add one more div with validation error message.
- <div *ngIf="username.touched && username.invalid" class="alert alert-danger">
- <div *ngIf="username.errors.required">Username is Required.</div>
- <div *ngIf="username.errors.minlength">Username should be minimum {{ username.errors.minlength.requiredLength }} characters.</div>
- <div *ngIf="username.errors.cannotContainSpace">Username cannot contain space.</div>
- <div *ngIf="username.errors.shouldBeUnique">Username is already taken.</div>
- </div>
Now let’s test this,

We can see the error message is showing but it will show on the screen after 2 seconds because we’ve a delay in setTimeout() of 2s. And our browser is not blocking, it is working in the delay as well.
Showing a Loader Image
When working with async validator you may want to display the loader image while the asynchronous operation is in progress. Implementation is very easy, let’s see how can we implement this feature.
Let’s add this div containing message just below the input username
- <div class="form-group">
- <label for="username">Username</label>
- <input
- formControlName="username"
- id="username"
- type="text"
- class="form-control">
- <div>Checking for Uniqueness...</div>
- <div *ngIf="username.touched && username.invalid" class="alert alert-danger">
- <div *ngIf="username.errors.required">Username is Required.</div>
- <div *ngIf="username.errors.minlength">Username should be minimum {{ username.errors.minlength.requiredLength }} characters.</div>
- <div *ngIf="username.errors.cannotContainSpace">Username cannot contain space.</div>
- <div *ngIf="username.errors.shouldBeUnique">Username is already taken.</div>
- </div>
- </div>
So we wanto to display this div while asynchronous is waiting for the result to come back from the server. But how do we know if our asynchronous validator is in progress? We know that
- formControlName="username"
this username is a property in our component and references to FormControl object. Our FormControl has a property called pending. Pending returns true if at least one async validator is in progress. So,
- <div *ngIf="username.pending">Checking for Uniqueness...</div>












Riddhi ValechaPosted Oct 5, 2018, 3:42 AM
Hello sir ... Extremely useful article... Sir .. I need help in doing css design in Angular 4 project ... I have shared my project at - https://www.c-sharpcorner.com/Forums/crud-operations-in-vs-code - It would be great if I get places where I have gone wrong.
Muthu KumarPosted Sep 13, 2018, 2:38 AM
Thanks for sharing. Very Nice. Step by Step Explanation also mentioning the errors part.