In this tutorial, we’ll explore reactive and template driven-forms in Angular. You’ll see how to create each kind and how to perform validation in Angular 6.
Reactive and Template-Driven Forms
What Are Angular Reactive Forms?
Reactive forms are also known as model-driven forms. This means that the HTML content changes depending on the code in the component.
What Are Angular Template-Driven Forms?
Template-driven forms are driven by derivatives in the template. This means that you will see derivatives such as ngModel
in the template as opposed to the code.
Differences Between Template-Driven and Reactive Forms
- Template-driven forms use the
FormsModule
, while reactive forms use theReactiveFormsModule
. - Template-driven forms are asynchronous, while reactive forms are synchronous.
- In template-driven forms, most of the interaction occurs in the template, while in reactive-driven forms, most of the interaction occurs in the component.
Advantages and Disadvantages of Template-Driven Forms
Although template forms are easier to create, they become a challenge when you want to do unit testing, because testing requires the presence of a DOM.
Advantages and Disadvantages of Reactive Forms
It’s easier to write unit tests in reactive forms since all the form code and functionality is contained in the component. However, reactive forms require more coding implementation in the component.
Creating and Validating Angular Forms
In this section, we’ll look at how to create and validate both kinds of forms. In both forms, we will create a contact form where users can submit data. We’ll start by creating an Angular application with two components as follows:
ng new angularforms ng generate component reactiveforms ng generate component templateforms
How to Create a Template Forms
The basic form template will be as follows:
Template Form
Next, we will add the ngModel
derivative to all the fields as shown. This is necessary to bind input fields to data model properties.
We then add the ngForm
and the ngSubmit
derivatives. ngForm
activates when the user clicks the submit button, while ngSubmit
specifies which function to run when the form is submitted.
We will then import the FormsModule
from @angular/forms
in app.module.ts in order to activate the template-driven forms.
import { FormsModule } from '@angular/forms'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, FormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
When a user inputs and submits data and clicks the submit button, we need to receive the data in the component class. Here, we just log the results to the console.
onSubmit(f) { console.log(f.value); }
You can also view the submitted data in real time when values are being typed to the form.
{{f.value.firstname}} {{f.value.lastname}} {{f.value.email}} {{f.value.message}}
Our form is now complete, and you can start testing by navigating to http://localhost:4200/template.
Angular Template Form Validation
Let’s see how we can add advanced features such as validation to our form. In this case, we are going to use some built-in validators which include:
-
required
—the form control should not have an empty field. -
minlength
—the form control should have a value of the specified minimum length. -
maxlength
—the form control should have a value of the specified maximum length. -
pattern
—the form control value should match a given regex value.
We will start by adding the required
attribute to all our input fields.
The submit button will be validated by use of the disabled
property, which will be set to true
if the form is valid.
Our working form should now look as shown below. As you can see, the submit button is disabled if all the fields are not filled, and the fields are also marked with an asterisk to show that they are mandatory.
Creating Angular Reactive Forms
Angular reactive forms are also known as model-driven forms. They employ a technique where the forms are designed in the component and then bindings are done for the HTML. They also make use of the following classes available in the ReactiveFormsModule
module.
-
FormGroup
FormControl
-
FormBuilder
We will only need the FormBuilder
API to create our form since our form is not complex. We will start by importing the module in the component class.
import {FormBuilder} from '@angular/forms'
The FormBuilder
makes it easy to scaffold, especially when building complex forms. We will use the group()
method available in FormBuilder
to create the FormGroup
instance and then add form controls as an object.
We will then inject it in the constructor via dependency injection.
export class ReactiveformsComponent implements OnInit { constructor(private formBuilder: FormBuilder){ } }
Let’s now use FormBuilder
to build our form models. Update reactiveforms.component.ts to look like this:
export class ReactiveformsComponent implements OnInit { form; constructor(private formBuilder: FormBuilder){ this.form = formBuilder.group({ firstname: [''], lastname: [''], email: ['', message: [''], }); } ngOnInit() { } }
In the above code, we use the FormBuilder
API and add our form fields in an object. We can now implement the template like a regular form. The only difference is that we need to tell Angular which formGroup
to use.
{{form.value.firstname}} Reactive Form
{{form.value.lastname}}
{{form.value.email}}
{{form.value.message}}
The last bit will be to implement the function that decides what happens when the form is submitted.
export class ReactiveformsComponent implements OnInit { ngOnInit() { } submit() { if (this.form.valid) { console.log(this.form.value) } else{ alert("FILL ALL FIELDS") } } }
Now that our form is complete, we can start testing. Navigate to http://localhost:4200/reactive, and as you type values for the input fields, the values should appear below the form as shown below.
Reactive Form Validation in Angular
We still need to add validation to our forms to ensure users don’t leave empty fields or enter the wrong data format.
We will first import the Validators
module in the component. The module is then added in the formGroup
fields.
constructor(private formBuilder: FormBuilder){ this.form = formBuilder.group({ firstname: ['', Validators.required], lastname: ['', Validators.required], email: ['', [Validators.required, Validators.email]], message: ['', Validators.required], }); }
We want all our fields to be mandatory, so we will update our fields with the formControlName
tag, which listens to changes in the value of the control.
That’s all it takes! Our Angular reactive form validation is now working, as shown below.
Conclusion
This tutorial has covered all the basics of creating and validating Angular forms. Try it out, and maybe you’ll even want to create your own custom validations.
The full source code to these example projects can be found in our GitHub repo.
Powered by WPeMatico