Angular Model-Driven Form Using VS Code And Node.js

Model-Driven Form(Reactive Form) 

 
In a model-driven approach, the model-driven form which is created in the .ts file is responsible for handling all the user interactions/validations. First, we need to create a model using Angular in-built classes like form group and form controls and then we need to bind a model in the HTML form.
 
Model-driven forms are more powerful and flexible.
 
These are some things that we can't do with template-driven forms,  but with the model-driven form, we can perform those things. If we want to detect if any changes are occurring in any variable we can do that with model-driven form. We can easily use two-way data binding in model-driven forms.
 
Reactive form in angular technique to manage your form in a reactive manner it means that you can manage your form and validation in our component.
 
These forms are the best option when we need a complex form.
 
It is easy to implement like using a model in control, with forms controls. These forms are called model-driven forms because of the model act as a mediator between the component and template. we need to import ReactiveFormsModule in our appModule.ts file.
 
In the .ts file, we need to import 3 more libraries (FormGroup, FormBuilder, and FormControl ).
  • FormControl:- it tracks the value of the controls and validates the invalid controls in the form. in the reactive form, we need to initialize FormControl object to use the functionality in our components, which engaged with Html component
  • FormGroup:- Tracks the validity and the state of the group of form control instance or moreover, we can say the FormGroup to be a collection of FormControls.
  • FormBuilder:- this helps us to the forms along with their initial value and their validations. 

Features of reactive forms or model-driven forms

 
There are few features of reactive form,
  1. More flexible
  2. no data binding is done
  3. More Component code and less Html markup
  4. reactive transformation is possible such as 
    1. Handling an event based on debounce time
    2. handling event when the components are distinct until changed 
    3. adding element dynamically 
  5. Handles any complex scenarios 
  6. Easler unit testing

Validation of the template-driven form

 
The most important part of any form is to add the validations in the application. when we do the fname: new FormControl(), the first arguments in the FormControl is the initial value and the second value is the validation that we can add there. 
 
validations are performed their works the same with both type form(template-driven form and model-driven form). 
 
Following are the classes,
  • ng-touched:- controls have been visited
  • ng-untouched:- controls have not to be visited
  • ng-dirty:- controls value have been changed
  • ng-pristine:- controls value have been changed
  • ng-valid:- controls value are valid
  • ng-invalid:- controls value are invalid
So in order to draw a border around the first name whenever the user visite any fields and don't add any value we need to add these classes.
 

Code of Model-driven Form

 
reactivecomponent.css
  1. .form-control{  
  2.     text-aligncenter;  
  3.     width200px;  
  4.     height40px;  
  5.     colorblack;  
  6.     border-colorblack;  
  7.     background-color: cornsilk;  
  8.     border-radius: 1px;  
  9.     border-style0.5px;  
  10. }  
  11. .btn-primary{  
  12.     text-aligncenter;  
  13.     border-radius: 6px;  
  14.     background-color#1976d2;  
  15.     width80px;  
  16.     height:30px;  
  17.     border-stylehidden;  
  18.     colorwhite;  
  19. }  
  20. input.ng-invalid.ng-touched{  
  21.     border-colorred;   
  22. }  
  23. .text{  
  24.     text-aligncenter;  
  25.     font-sizex-large;  
  26. }  
  27. .container{  
  28.     text-aligncenter;  
  29. }  
reactivecomponent.html
  1. <h1 class="text">Welcome to {{title}}</h1>    
  2. <div class="container">    
  3.   <div class="row">    
  4.     <div class="form-bg">    
  5.       <form [formGroup]='signupForm' (ngSubmit)='PostData(signupForm)'>    
  6.         <div class="form-group">    
  7.           <input type="text" class="form-control" formControlName='fname' placeholder="Your first name" >    
  8.               
  9.         </div>    
  10.         <br>    
  11.         <div class="form-group" >    
  12.           <input type="text" class="form-control" formControlName="lname" placeholder="enter lastname" >    
  13.         </div>    
  14.         <br>    
  15.         <div class="form-group">    
  16.           <input type="email" class="form-control" formControlName="email" placeholder="Enter Your email" >    
  17.         </div>    
  18.         <br>    
  19.         <div class="form-group">    
  20.           <input type="password" class="form-control" formControlName="password" placeholder="Enter your Password">    
  21.         </div>    
  22.         <br>    
  23.         <br>    
  24.         <div>    
  25.         <input type="submit" class="btn-primary" value="PostData" [disabled]='!signupForm.valid'>    
  26.           </div>    
  27.       </form>    
  28.     </div>    
  29.   </div>    
  30. </div>    
reactivecomponent.ts
  1. import { Component, OnInit } from '@angular/core';  
  2. import {FormControl,FormGroup,FormBuilder, NgForm,Validator, Validators } from '@angular/forms'  
  3. @Component({  
  4.   selector: 'app-reactive',  
  5.   templateUrl: './reactive.component.html',  
  6.   styleUrls: ['./reactive.component.css']  
  7. })  
  8. export class ReactiveComponent{  
  9. title='reactive form ';  
  10. signupForm:FormGroup;  
  11. FirstName:string="";  
  12. LastName:string="";  
  13. Email:string="";  
  14. Password:string="";  
  15.   
  16.   constructor(private frmbuilder:FormBuilder){  
  17.     this.signupForm=frmbuilder.group({  
  18. /*fname:new FormControl(), 
  19.       lname:new FormControl(), 
  20.       email:new FormControl(), 
  21.       password:new FormControl()*/  
  22.         
  23.       fname:['',[Validators.required,Validators.minLength(1)]],  
  24.       lname:['',[Validators.required,Validators.minLength(1)]],  
  25.       email:['', [Validators.required,Validators.email]],  
  26.       password:['', [Validators.required,Validators.minLength(8)]]  
  27.     });  
  28.   
  29.   
  30.   }  
  31.   PostData(signupForm:any){  
  32.     this.FirstName=signupForm.controls.fname.value;  
  33.     this.LastName=signupForm.controls.lname.value;  
  34.     this.Email=signupForm.controls.email.value;  
  35.     this.Password=signupForm.controls.password.value;  
  36.     console.log(this.FirstName);  
  37.     console.log(this.LastName);  
  38.     console.log(this.Email);  
  39.     console.log(this.LastName);  
  40.   
  41.   console.log(signupForm.controls);  
  42.   }  
  43.   }  
appModule.ts
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import { AppComponent } from './app.component';  
  4. import {FormsModule} from '@angular/forms';  
  5. import { ReactiveFormsModule} from '@angular/forms'  
  6. import { ReactiveComponent } from './reactive/reactive.component';  
  7. import { CheckserviceComponent } from './checkservice/checkservice.component'  
  8. import { UserService } from './user.service';  
  9. import { PostdataComponent } from './postdata/postdata.component';  
  10. @NgModule({  
  11.   declarations: [  
  12.     AppComponent,  
  13.     ReactiveComponent,  
  14.     CheckserviceComponent,CheckserviceComponent, PostdataComponent  
  15.   ],  
  16.   imports: [  
  17.     BrowserModule,FormsModule,ReactiveFormsModule  
  18.   ],  
  19.   providers: [UserService],  
  20.   bootstrap: [ReactiveComponent]  
  21. })  
  22. export class AppModule { }  
 now compile this all components with command ng serve after compile all component successfully, open the browser and hit localhost:4200. browser display output like this,
 
Now you can see the postdata button is disabled. now you fill the details in the form for checking the form validations, we left empty few fields then see the form how it is looking like this.
 
 
Now you can see the form empty field is red because the user touched these fields but can't add any value in the fields. The postdata button is disabled now. that means our forms validations are working properly. 
 
Now fill valid details in all in the fields. see how the form looking,
 
 
Now you can see the form all fields value are valid. and the post data button is enabled now. now go to the console and check the errors.
 
 
Now press the postdata button and check,
 
Now you can see console don't have any errors, now press the postdata button and check all values are stored in console or not.
 
 
now you can see all values are stored in the console and our forms are working properly.
 
I hope you enjoy this article. to learn more technologies or logics to follow c#corner or c sharp corner.com 


Similar Articles