Home >>Angular7 Tutorial >Angular7 Forms

Angular7 Forms

Angular7 Forms

In this chapter, we'll look at how Angular 7 uses forms. We will discuss two ways to deal with forms –

  • Template driven form
  • Model driven form

Template Driven Form

Most of the work is done in the template, with a template guided type. Most of the work is done in component class with the model driven form.

Let's consider working on the driven Template form now. We must create a quick login form and fill in the form with the email I d, password and submit button. To continue with, we need to import from @angular/forms to FormsModule that is done as follows in app.module.ts –


import { BrowserModule } from '@angular/platform-browser'; 
import { NgModule } from '@angular/core';
import { AppRoutingModule , RoutingComponent} from './app-routing.module'; 
import { AppComponent } from './app.component'; 
import { NewCmpComponent } from './new-cmp/new-cmp.component'; 
import { ChangeTextDirective } from './change-text.directive'; 
import { SqrtPipe } from './app.sqrt'; 
import { MyserviceService } from './myservice.service'; 
import { HttpClientModule } from '@angular/common/http'; 
import { ScrollDispatchModule } from '@angular/cdk/scrolling'; 
import { DragDropModule } from '@angular/cdk/drag-drop'; 
import { FormsModule } from '@angular/forms';

@NgModule({ 
   declarations: [
      SqrtPipe, 
      AppComponent, 
      NewCmpComponent, 
      ChangeTextDirective, 
      RoutingComponent 
   ],
   imports: [ 
      BrowserModule, 
      AppRoutingModule, 
      HttpClientModule, 
      ScrollDispatchModule, 
      DragDropModule, 
      FormsModule 
   ], 
   providers: [MyserviceService], 
   bootstrap: [AppComponent] 
}) 
export class AppModule { }

So we imported the FormsModule in app.module.ts and the same is included in the list of imports as shown in the highlighted code.

Let's build our form in the app.component.html file.


<form #userlogin = "ngForm" (ngSubmit) = "onClickSubmit(userlogin.value)"> 
   <input type = "text" name = "emailid" placeholder = "emailid" ngModel> 
   <br/> 
   <input type = "password" name = "passwd" placeholder = "passwd" ngModel> 
   <br/> 
   <input type = "submit" value = "submit"> 
</form>

We have created a simple form with email I d, password and the submit button for input tags. We assigned it to type, name and placeholder.

We need to create model form controls in template driven forms by adding the ngModel directive and the name attribute. So wherever we want Angular to access our data from the forms, add ngModel as shown above to that name. Now, if we need to read the emailid and passwd, then we need to add the ngModel into it.

If you see, we added the ngForm to the # userlogin, too. You need to attach the ngForm directive to the form template that we created. We've also added onClickSubmit function and assigned userlogin.value to it.

Let's build the function in the app.component.ts now, and get the values in the form entered.


import { Component } from '@angular/core'; 
import { MyserviceService } from './myservice.service';

@Component({ 
   selector: 'app-root', 
   templateUrl: './app.component.html', 
   styleUrls: ['./app.component.css']
})
export class AppComponent { 
   title = 'Angular 7 Project!'; 
   constructor(private myservice: MyserviceService) { } 
   ngOnInit() { } 
   onClickSubmit(data) {
      alert("Entered Email id : " + data.emailid); 
   }
}

We have specified the function onClickSubmit in the app.component.ts file above. Clicking on the submit form button will result in the check coming to the function above.

In app.component.css the css for the login form is added –


input[type = text], input[type = password] { 
   width: 40%; 
   padding: 12px 20px; 
   margin: 8px 0; 
   display: inline-block; 
   border: 1px solid #B3A9A9; 
   box-sizing: border-box; 
} 
input[type = submit] { 
   padding: 12px 20px; 
   margin: 8px 0; 
   display: inline-block; 
   border: 1px solid #B3A9A9; 
   box-sizing: border-box; 
}

Model Driven Form

We have to import the ReactiveFormsModule from @angular / forms in the model driven form, and use the same in the import array.

There is a change going into app.module.ts.


import { BrowserModule } from '@angular/platform-browser'; 
import { NgModule } from '@angular/core';
import { AppRoutingModule , RoutingComponent} from './app-routing.module'; 
import { AppComponent } from './app.component'; 
import { NewCmpComponent } from './new-cmp/new-cmp.component'; 
import { ChangeTextDirective } from './change-text.directive'; 
import { SqrtPipe } from './app.sqrt'; 
import { MyserviceService } from './myservice.service'; 
import { HttpClientModule } from '@angular/common/http'; 
import { ScrollDispatchModule } from '@angular/cdk/scrolling'; 
import { DragDropModule } from '@angular/cdk/drag-drop';
import { ReactiveFormsModule } from '@angular/forms';

@NgModule({ 
   declarations: [ 
      SqrtPipe, 
      AppComponent, 
      NewCmpComponent, 
      ChangeTextDirective, 
      RoutingComponent 
   ],
   imports: [ 
      BrowserModule, 
      AppRoutingModule, 
      HttpClientModule, 
      ScrollDispatchModule, 
      DragDropModule, 
      ReactiveFormsModule 
   ], 
   providers: [MyserviceService], 
   bootstrap: [AppComponent] 
}) 
export class AppModule { }

We need to import a few modules for the model guided form at app.component.ts. For example, from '@angular/forms' import { FormGroup, FormControl }.


import { Component } from '@angular/core'; 
import { MyserviceService } from './myservice.service'; 
import { FormGroup, FormControl } from '@angular/forms';

@Component({ 
   selector: 'app-root', 
   templateUrl: './app.component.html', 
   styleUrls: ['./app.component.css'] 
})
export class AppComponent {
   title = 'Angular 7 Project!'; 
   emailid; 
   formdata;
   constructor(private myservice: MyserviceService) { }  
   ngOnInit() { 
      this.formdata = new FormGroup({ 
         emailid: new FormControl("angular@gmail.com"),
         passwd: new FormControl("abcd1234") 
      }); 
   } 
   onClickSubmit(data) {this.emailid = data.emailid;}
}

At the beginning of the class the variable form data is initialized, and the same is initialized with FormGroup as shown above. The emailid and passwd variables are initialized with default values to show in the form. You can keep it blank if you want to.

We have used formdata to initialize the form values; in the form UI app.component.html, we must use the same.


<div> 
   <form [formGroup] = "formdata" (ngSubmit) = "onClickSubmit(formdata.value)" > 
      <input type = "text" class = "fortextbox" name = "emailid" placeholder = "emailid" 
         formControlName = "emailid"> 
      <br/> 
      
      <input type = "password" class = "fortextbox" name = "passwd" 
         placeholder = "passwd" formControlName = "passwd"> 
      <br/>
      
      <input type = "submit" class = "forsubmit" value = "Log In"> 
   </form>
</div> 
<p> Email entered is : {{emailid}} </p>

We used formGroup for the form in the.html file in square bracket; for example, [formGroup] = "formdata." The function onClickSubmit, for which formdata.value is passed, is called upon submit.

Uses the formControlName input tag. A value is given which we used in the file app.component.ts.

The control will pass to the onClickSubmit function, which is defined in the app.component.ts file, when you click Send.

Form Validation

Let's explore validation of the form now using model guided design. You can either use the built-in validation form, or use the custom validation approach. In the form we shall use both approaches. The same example we created in one of our previous sections will continue. We need to import validators from @angular / forms with Angular 7 as shown below –

import { FormGroup, FormControl, Validators} from '@angular/forms'

Angular has incorporated validators including mandatory field, minlength, maxlength, and pattern. Those are to be accessed through the module Validators.

You can simply add validators or an array of validators needed to tell Angular if a specific field is mandatory. Let's try the same on one of the textboxes input, that is, email I d. We added the following validation parameters for the e-mail Id –

  • Required
  • Pattern matching

In app.component.ts, this is how a code is validated.


import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators} from '@angular/forms';

@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent {
   title = 'Angular 4 Project!';
   todaydate;
   componentproperty;
   emailid;
   formdata;
   ngOnInit() {
      this.formdata = new FormGroup({
         emailid: new FormControl("", Validators.compose([
            Validators.required,
            Validators.pattern("[^ @]*@[^ @]*")
         ])),
         passwd: new FormControl("")
      });
   }
   onClickSubmit(data) {this.emailid = data.emailid;}
}

In Validators.compose, you can add the list of things in the input field you want to validate. Right now, we've added the necessary parameters and pattern matching to take only valid email.

The submit button is disabled in the app.component.html if any of the inputs to the form are not valid. This works as follows −


<div> 
   <form [formGroup] = "formdata" (ngSubmit) = "onClickSubmit(formdata.value)"> 
      <input type = "text" class = "fortextbox" name = "emailid" 
         placeholder = "emailid" formControlName = "emailid"> 
      <br/> 
    
      <input type = "password" class = "fortextbox" name = "passwd" 
         placeholder = "passwd" formControlName = "passwd">
      <br/> 
      
      <input type = "submit" [disabled] = "!formdata.valid" class = "forsubmit" 
         value = "Log In"> 
   </form> 
</div>
<p> Email entered is : {{emailid}} </p>

We've added disabled in the square bracket for the submission button, which is given the following value.

!formdata.valid.

Thus, if the formdata.valid is not valid, the button remains disabled and the user can not submit it.


No Sidebar ads