Angular 8 Reactive Form
In angular we have two type of form and according to our requirement we can use them.
In general:
In this article we will learn how to use reactive form along with bootstrap.
You can check out the more about reactive form here
You also need Angular CLI 8 installed otherwise, you can simply run the npm install -g @angular/cli command to install it.
Assuming that you have already installed the Angular CLI in your system, let's create an Angular app using the Angular CLI command.
We will add routing and for stylesheet format we will select CSS
Just wait for some time CLI will generate all the necessary source and configuration files and install the npm dependencies. Routing will also be available for you.
In general:
- Reactive forms are more robust: they're more scalable, reusable, and testable. If forms are a key part of your application, or you're already using reactive patterns for building your application, use reactive forms.
- Template-driven forms are useful for adding a simple form to an app, such as an email list signup form. They're easy to add to an app, but they don't scale as well as reactive forms. If you have very basic form requirements and logic that can be managed solely in the template, use template-driven forms.
In this article we will learn how to use reactive form along with bootstrap.
You can check out the more about reactive form here
Prerequisites
You need to have Node.js and npm installed on your system.You also need Angular CLI 8 installed otherwise, you can simply run the npm install -g @angular/cli command to install it.
Creating registration form
Let’s start fresh with creating an angular 8 app.Assuming that you have already installed the Angular CLI in your system, let's create an Angular app using the Angular CLI command.
$ ng n new-app |
We will add routing and for stylesheet format we will select CSS
Just wait for some time CLI will generate all the necessary source and configuration files and install the npm dependencies. Routing will also be available for you.
Adding bootstrap
Now we are ready to add the bootstrap into our new app. We will use CLI to add the Bootstrap 4 in our project.$ npm install bootstrap@4 jquery --save |
Now after this we will add the bootstrap reference in anglar.json. We will copy the relevant path of bootstrap and add it in ‘styles’ as shown in the below screenshot.
Run our new app
Let’s build our app by using ng build command and the run it by using below command.$ ng serve --open |
By default our application will run on 4200 port. Below is the screenshot for the same.
Add Component
We will be adding a new component with the below CLI command.$ ng g c register |
It will be generated in src/app location.
Now let’s add routing for our new module
Open the src/app/app-routing.module.ts file and the following changes:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { RegisterComponent } from './register/register.component';
const routes: Routes = [
{ path: 'register', component: RegisterComponent },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Let's remove this default HTML code. Open the src/app/app.component.html remove everything but leave <router-outlet>
Below will be our app.component.html file
<router-outlet></router-outlet>
Creating register form using Angular 8 and reactive form
Before
using reactive forms in Angular we need to import
FormsModule
and ReactiveFormsModule
in the application
module.
Open
the
src/app/app.module.ts
file and update it
accordingly:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { RegisterComponent } from './register/register.component';
import { FormsModule, ReactiveFormsModule} from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
RegisterComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
ReactiveFormsModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Open the src/app/register.component.ts file and import:
- FormBuilder, FormGroup, Validators symbols
that are used to create Angular reactive forms,
- Router for routing
import { Component, OnInit } from '@angular/core';
import { FormGroup, Validators, FormBuilder } from '@angular/forms';
Next, inject the
FormBuilder
via the service
constructor:
constructor(private formBuilder: FormBuilder) {
}
Next,
add these service variables:
registerForm: FormGroup;
submitted = false;
countryInfoList = [{'CountryId': 1, 'CountryName': 'USA'},
{'CountryId': 2, 'CountryName': 'India'}];
stateInfoList = [{'StateId': 1, 'StateName': 'Delhi'},
{'StateId': 2, 'StateName': 'Chandigarh'}];
Next, in thengOnInit()
life-cycle event, create the form:
ngOnInit() {
this.registerForm = this.formBuilder.group({
firstName: ['', Validators.required],
middleName: [''],
lastName: ['', Validators.required],
email: ['', [Validators.required, Validators.email]],
password: ['', [Validators.required, Validators.minLength(6)]],
addressline1: [''],
addressline2: [''],
city: [''],
zip: [''],
countryId:['2'],
stateId:['2'],
iAccept:[true]
});
}
Next,
add a get property to make easy to access the form controls on the HTML form:
get f() {
return this.registerForm.controls;
}
Finally,
add the
onSubmit()
method:
async onSubmit() {
this.submitted = true;
// stop here if form is invalid
if (this.registerForm.invalid) {
return;
}
alert('SUCCESS!! :-)\n\n' + JSON.stringify(this.registerForm.value))
}
Implmenting HTML
Open the
src/app/register.component.html
file
and add:
<div class="container">
<h1 class="well">Registration Form</h1>
<div class="col-lg-12 well">
<h1 class="well">Registration Form</h1>
<div class="col-lg-12 well">
<form [formGroup]="registerForm" (ngSubmit)="onSubmit()">
<div class="form-row">
<div class="form-group
col-md-4">
<label>First Name</label>
<input type="text" formControlName="firstName" class="form-control" [ngClass]="{ 'is-invalid':
submitted && f.firstName.errors }" />
<div *ngIf="submitted &&
f.firstName.errors" class="invalid-feedback">
<div *ngIf="f.firstName.errors.required">First Name is required</div>
</div>
</div>
<div class="form-group
col-md-4">
<label>Middle Name</label>
<input type="text" formControlName="middleName" class="form-control" />
</div>
<div class="form-group
col-md-4">
<label>Last Name</label>
<input type="text" formControlName="lastName" class="form-control" [ngClass]="{ 'is-invalid':
submitted && f.lastName.errors }" />
<div *ngIf="submitted &&
f.lastName.errors" class="invalid-feedback">
<div *ngIf="f.lastName.errors.required">Last Name is required</div>
</div>
</div>
</div>
<div class="form-row">
<div class="form-group
col-md-6">
<label>Email</label>
<input type="text" formControlName="email" class="form-control" [ngClass]="{ 'is-invalid':
submitted && f.email.errors }" />
<div *ngIf="submitted &&
f.email.errors" class="invalid-feedback">
<div *ngIf="f.email.errors.required">Email is required</div>
<div *ngIf="f.email.errors.email">Email must be a valid email
address</div>
</div>
</div>
<div class="form-group
col-md-6">
<label>Password</label>
<input type="password" formControlName="password" class="form-control" [ngClass]="{ 'is-invalid':
submitted && f.password.errors }" />
<div *ngIf="submitted &&
f.password.errors" class="invalid-feedback">
<div *ngIf="f.password.errors.required">Password is required</div>
<div *ngIf="f.password.errors.minlength">Password must be at least 6
characters</div>
</div>
</div>
</div>
<div class="form-group">
<label>Address Line 1</label>
<input type="text" class="form-control" formControlName="addressline1" placeholder="1234 Main St">
</div>
<div class="form-group">
<label>Address Line 2</label>
<input type="text" class="form-control" formControlName="addressline2" placeholder="Apartment, studio, or
floor">
</div>
<div class="form-row">
<div class="form-group
col-md-6">
<label>City</label>
<input type="text" class="form-control" formControlName="city">
</div>
<div class="form-group
col-md-6">
<label>Zip</label>
<input type="text" class="form-control" formControlName="zip">
</div>
</div>
<div class="form-row">
<div class="form-group
col-md-6">
<label for="country">Country</label>
<select formControlName="countryId" class="form-control">
<option *ngFor="let country of
countryInfoList" [value]="country.CountryId">
{{country.CountryName}}
</option>
</select>
</div>
<div class="form-group
col-md-6">
<label for="inputState">State</label>
<select formControlName="stateId" class="form-control">
<option *ngFor="let state of
stateInfoList" [value]="state.StateId">
{{state.StateName}}
</option>
</select>
</div>
</div>
<div class="form-group">
<div class="form-check">
<input class="form-check-input" type="checkbox" formControlName="iAccept">
<label class="form-check-label">
I Accept
</label>
</div>
</div>
<div class="form-group">
<button class="btn btn-primary">Register</button>
</div>
</form>
</div>
I have used bootstrap class to style our register form.
Run the application on browser you will get the nice
and tidy registration form as shown below
As we have used form validation and added validation
to few of our field below screenshot is with the validation message
Conclusion
Today we have learned the following- Creating new angular app using CLI
- Adding bootstrap and using it in our registration form
- Creating a new reactive form
- Applying validation on the different field like string, email
- Binding dropdown
- 2 way binding (pre populating dropdown and checkbox)
You can download the code here
Nice articel, This article help me very well. Thank you. Also please check my article on my site about What Is Angular?.
ReplyDelete