Hide/Show Form Fields Using Angular Forms

Introduction 

 
In this article, I will explain about hiding and showing form fields using Angular forms. Forms are used in web applications that enable the users to enter data and process the data from it.
        
Generally speaking, Angular forms are of two types, they are Reactive Forms and Template-Driven forms. First of all, the reactive forms are known to be model-driven forms because all the work will be done in component class, whereas template-driven forms are template-based. So, template-driven forms will allow using login forms and functions to work on template-based forms. Here in this article, we will be using template-driven forms along with using the Bootstrap UI library. You can find more information about forms from the following links.
 
So, coming to the point -- we are going to show/hide form fields. For that, I have created a child component and by using bootstrap library forms I have created a form with two blocks of personal details and communication details.
 
For creating a new component use the following command to create a new component.
 
ng g c ComponentName
 
The ComponentName represents the component name that the user wants to create and I have created a child component named as an employee.
 
Now open employee.component.html and place the code as represented below.
  1. <div class="container-fluid">    
  2.     <div *ngIf="(showmode=='Register')">    
  3.         <form #frmEmployee="ngForm" (ngSubmit)="frmEmployee.form.valid && OnSubmit(frmEmployee)">    
  4.             <div class="row" *ngIf="(ObjConfiguration.showpersonalDetails)">    
  5.                 <div class="col-md-12">    
  6.                     <strong>    
  7.                         <h5>Personal Details </h5>    
  8.                     </strong>    
  9.                 </div>    
  10.                 <div class=" col-md-4 form-group" *ngIf="(ObjConfiguration.showname)">    
  11.                     <label> Name</label>    
  12.                     <input type="text" class=" form-control text-uppercase" [(ngModel)]="objEmp.PersonalDetails.Name" name="Username"    
  13. id="Username" maxlength="50" #Username="ngModel" required>    
  14.                         <small class="text-danger" *ngIf="Username.invalid && (Username.touched || frmEmployee.submitted)">Employee Name is required</small>    
  15.                     </div>    
  16.                     <div class=" col-md-4 form-group" *ngIf="(ObjConfiguration.showdob)">    
  17.                         <label>DOB</label>    
  18.                         <input type="date" class="form-control" [(ngModel)]="objEmp.PersonalDetails.Dob" name="Dob" id="Dob"    
  19. #Dob="ngModel" (blur)="OnDate($event)" required >    
  20.                             <small class="text-danger" *ngIf="Dob.invalid && (frmEmployee.submitted || Dob.touched)">Dob is required!</small>    
  21.                             <small class="text-danger" *ngIf="Dob.valid && !IsMinDate">Date should be minimum 2019-01-01</small>    
  22.                             <small class="text-danger" *ngIf="Dob.valid && !IsMaxDate">Date should be maximum 2025-01-01</small>    
  23.                         </div>    
  24.                         <div class="col-md-4 form-group" *ngIf="(ObjConfiguration.showmobile)">    
  25.                             <label>Mobile</label>    
  26.                             <input type="text" maxlength="10" class="form-control" [(ngModel)]="objEmp.PersonalDetails.Mobile" name="Mobile" id="Mobile"    
  27. #Mobile="ngModel" pattern="^\d{10}$" required>    
  28.                                 <div *ngIf="Mobile.invalid && (frmEmployee.submitted || Mobile.touched)">    
  29.                                     <small class="text-danger" *ngIf="Mobile.errors.required">Mobile Number is required</small>    
  30.                                     <small class="text-danger" *ngIf="Mobile.errors.pattern">Mobile number must be 10 digits</small>    
  31.                                 </div>    
  32.                             </div>    
  33.                             <div class="col-md-4 form-group" *ngIf="(ObjConfiguration.showemail)">    
  34.                                 <label>Email ID</label>    
  35.                                 <input type="email" class="form-control" [(ngModel)]="objEmp.PersonalDetails.Email" name="Email" id="Email"    
  36. #Email="ngModel" pattern="^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$" required>    
  37.                                     <div *ngIf="Email.invalid && (frmEmployee.submitted || Email.touched) ">    
  38.                                         <small class="text-danger" *ngIf="Email.errors.required">Email is required</small>    
  39.                                         <small class="text-danger" *ngIf="Email.errors.pattern">Email must be proper format like @ ,.com</small>    
  40.                                     </div>    
  41.                                 </div>    
  42.                                 <div class="col-md-4 form-group" *ngIf="(ObjConfiguration.showgender )">    
  43.                                     <label>Gender</label>    
  44.                                     <select name="Gender" class="form-control" #Gender="ngModel" [(ngModel)]="objEmp.PersonalDetails.Gender"    
  45. required>    
  46.                                         <option *ngFor="let item of Genders" [value]="item">    
  47. {{item}}    
  48. </option>    
  49.                                     </select>    
  50.                                     <small class="text-danger" *ngIf="Gender.invalid && (Gender.touched || frmEmployee.submitted)">Gender is required</small>    
  51.                                 </div>    
  52.                             </div>    
  53.                             <hr class="line">    
  54.                                 <div class="row" *ngIf="(ObjConfiguration.showcommdetails)">    
  55.                                     <h5 class="ml-2 col-md-12 mb-3">    
  56.                                         <strong>Communication Details</strong>    
  57.                                     </h5>    
  58.                                     <div class="col-md-4 form-group" *ngIf="(ObjConfiguration.IsStreet)">    
  59.                                         <label>Street</label>    
  60.                                         <input type="text" class=" form-control text-uppercase" [(ngModel)]="objEmp.CommunicationDetails.Street" name="Street"    
  61. id="Street" maxlength="50" #Street="ngModel" required>    
  62.                                             <small class="text-danger"    
  63. *ngIf="Street.invalid && (Street.touched || frmEmployee.submitted) && ObjConfiguration.IscommMandatory">Street is required</small>    
  64.                                         </div>    
  65.                                         <div class="col-md-4 form-group" *ngIf="(ObjConfiguration.IsArea)" >    
  66.                                             <label>Area</label>    
  67.                                             <input type="text" class=" form-control text-uppercase" [(ngModel)]="objEmp.CommunicationDetails.Area" name="Area" id="Area"    
  68. #Area="ngModel" maxlength="50" required>    
  69.                                                 <small class="text-danger" *ngIf="Area.invalid && (Area.touched || frmEmployee.submitted) && ObjConfiguration.IscommMandatory">Area is    
  70. required</small>    
  71.                                             </div>    
  72.                                             <div class="col-md-4 form-group " *ngIf="(ObjConfiguration.IsDistrict)" >    
  73.                                                 <label>District</label>    
  74.                                                 <input type="text" class="form-control text-uppercase" [(ngModel)]="objEmp.CommunicationDetails.District" name="District"    
  75. id="District" maxlength="50" #District="ngModel" required>    
  76.                                                     <small class="text-danger"    
  77. *ngIf="District.invalid && (District.touched || frmEmployee.submitted) && ObjConfiguration.IscommMandatory">District is    
  78. required</small>    
  79.                                                 </div>    
  80.                                                 <div class="col-md-4 form-group" *ngIf="(ObjConfiguration.IsState)">    
  81.                                                     <label>State</label>    
  82.                                                     <input type="text" class="form-control text-uppercase" [(ngModel)]="objEmp.CommunicationDetails.State" name="State"    
  83. id="State" maxlength="50" #State="ngModel" required>    
  84.                                                         <small class="text-danger" *ngIf="State.invalid && (State.touched || frmEmployee.submitted) && ObjConfiguration.IscommMandatory">State    
  85. is required</small>    
  86.                                                     </div>    
  87.                                                     <div class="col-md-4 form-group" *ngIf="(ObjConfiguration.IsPincode)" >    
  88.                                                         <label>Pincode</label>    
  89.                                                         <input type="text" class=" form-control" [(ngModel)]="objEmp.CommunicationDetails.pincode" name="pincode"    
  90. id="pincode" maxlength="6" #pincode="ngModel" required>    
  91.                                                             <small class="text-danger"    
  92. *ngIf="pincode.invalid && (pincode.touched || frmEmployee.submitted) && ObjConfiguration.IscommMandatory">pincode is required</small>    
  93.                                                         </div>    
  94.                                                     </div>    
  95.                                                     <div class="text-right m-2 ">    
  96.                                                         <button class="btn btn-primary " type="submit">Submit</button>    
  97.                                                         <button class="btn btn-danger ml-2" style="float:right" type="reset">Reset</button>    
  98.                                                     </div>    
  99.                                                 </form>    
  100.                                             </div>    
  101.                                         </div>    
So here I have created two blocks namely, personal details and communication details, and I also have done the form validation using the template-driven method.
 
The next step is to create a model, for creating a model file use the following command to create a class file.
 
ng g class employee
 
Open employee.ts file and place the code inside the model file as represented below.
  1. export class PersonalDetails {  
  2.  public Name: string;  
  3.  public Dob: string;  
  4.  public Mobile: string;  
  5.  public Email: string;  
  6.  public Gender: string;  
  7. }  
  8. export class CommunicationDetails {  
  9.  public Street: string;  
  10.  public Area: string;  
  11.  public District: string;  
  12.  public State: string;  
  13.  public pincode: string;  
  14. }  
  15. export class Employee {  
  16.  public PersonalDetails: PersonalDetails = new PersonalDetails();  
  17.  public CommunicationDetails: CommunicationDetails = new CommunicationDetails();  
  18. }  
  19. export class Configuration {  
  20.  public showcommdetails: boolean;  
  21.  public IsStreet: boolean;  
  22.  public IsArea: boolean;  
  23.  public IsDistrict: boolean;  
  24.  public IsState: boolean;  
  25.  public IsPincode: boolean;  
  26.  public showpersonalDetails: boolean;  
  27.  public Isname: boolean;  
  28.  public showname: olean;  
  29.  public showmobile: boolean;  
  30.  public showdob: boboolean;  
  31.  public showemail: boolean;  
  32.  public showgender: boolean;  
  33. }  
Next, we can keep on proceeding to the next step. Now we can create a service file, for creating a service file use the following command:
ng g service EmployeeService
 
Now open employee.component.ts file and replace the following code as given below.
  1. import {  
  2.  Component,  
  3.  OnInit  
  4. } from '@angular/core';  
  5. import {  
  6.  EmployeeService  
  7. } from '../employee.service';  
  8. import {  
  9.  Employee,  
  10.  Configuration  
  11. } from 'src/employee';  
  12. @Component({  
  13.  selector: 'app-employee',  
  14.  templateUrl: './employee.component.html',  
  15.  styleUrls: ['./employee.component.css']  
  16. })  
  17. export class EmployeeComponent implements OnInit {  
  18.  public showmode: string;  
  19.  public objEmp: Employee;  
  20.  public ObjConfiguration: Configuration;  
  21.  Genders = ['Male''Female'];  
  22.  constructor(private srvEmployee: EmployeeService) {  
  23.   this.showmode = 'Register';  
  24.   this.objEmp = new Employee();  
  25.   this.ObjConfiguration = new Configuration();  
  26.  }  
  27.  ngOnInit() {  
  28.   this.srvEmployee.getConfig().subscribe(data => this.ObjConfiguration = data);  
  29.  }  
  30. }  
The next step is to open the employee.service.ts file and replace the following code inside it as given below.
  1. import {  
  2.  Injectable  
  3. } from '@angular/core';  
  4. import {  
  5.  Employee,  
  6.  Configuration  
  7. } from '../employee';  
  8. import {  
  9.  HttpClient  
  10. } from '@angular/common/http';  
  11. import {  
  12.  Observable  
  13. } from 'rxjs';  
  14. @Injectable({  
  15.  providedIn: 'root'  
  16. })  
  17. export class EmployeeService {  
  18.  public Url = '/assets/config.json';  
  19.  constructor(private http: HttpClient) {}  
  20.  public getConfig(): Observable < Configuration > {  
  21.   return this.http.get < Configuration > (this.Url);  
  22.  }  
  23. }  
The main goal of this article to hide and show the form fields in the form, so here comes the main part -- we need to create a JSON file so with the help of JSON file we can show/hide the form fields (or) we can hide/show the blocks of the forms.
 
For creating a JSON file just right click->on assets folder and create a file named as config.json and open the config.json file and place the following code to JSON file as mentioned below.
 
 
  1. {  
  2.  "showcommdetails"true,  
  3.  "IsStreet"false,  
  4.  "IsArea"true,  
  5.  "IsDistrict"true,  
  6.  "IsState"true,  
  7.  "IsPincode"true,  
  8.  "showpersonalDetails"true,  
  9.  "Isname"true,  
  10.  "showname"true,  
  11.  "showdob"false,  
  12.  "showmobile"true,  
  13.  "showemail"true,  
  14.  "showgender"true  
  15. }  
The final step is to compile the Angular project and view the output in the browser. For compiling, use the following command to see the output
 
ng serve -open
 
 
 
Now we can the output representing the form with two blocks namely as personal details and communication details. Now we are going to hide a particular block, for that open config.json file and change “showcommdetails”: true, to “showcommdetails”: false, Now we can refresh the browser and we can see that communication details block has been hidden and we can only see the personal details, again change the value to “showcommdetails”: true, to see the changes
 
 
 
 
 
Likewise, change “showpersonalDetails”: true, to “showpersonalDetails”: false, in config.json file and refresh the browser to view the changes, so we can view that personal details block has been hidden.
 
 
 
 
 
So far, we have seen hiding/showing form blocks alone, now we can hide/show particular field, for example: I am going to hide a particular field named DOB so for that open config.json file and change “showdob”: true, to “showdob”:false, and refresh the browser to see the changes and we can see that the DOB field has been hidden.
 
 
 
 

Summary

 
In this article we have seen ways of hiding/ showing the form fields and also for form block. I hope this article will be useful for you.