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.
- <div class="container-fluid">
- <div *ngIf="(showmode=='Register')">
- <form #frmEmployee="ngForm" (ngSubmit)="frmEmployee.form.valid && OnSubmit(frmEmployee)">
- <div class="row" *ngIf="(ObjConfiguration.showpersonalDetails)">
- <div class="col-md-12">
- <strong>
- <h5>Personal Details </h5>
- </strong>
- </div>
- <div class=" col-md-4 form-group" *ngIf="(ObjConfiguration.showname)">
- <label> Name</label>
- <input type="text" class=" form-control text-uppercase" [(ngModel)]="objEmp.PersonalDetails.Name" name="Username"
- id="Username" maxlength="50" #Username="ngModel" required>
- <small class="text-danger" *ngIf="Username.invalid && (Username.touched || frmEmployee.submitted)">Employee Name is required</small>
- </div>
- <div class=" col-md-4 form-group" *ngIf="(ObjConfiguration.showdob)">
- <label>DOB</label>
- <input type="date" class="form-control" [(ngModel)]="objEmp.PersonalDetails.Dob" name="Dob" id="Dob"
- #Dob="ngModel" (blur)="OnDate($event)" required >
- <small class="text-danger" *ngIf="Dob.invalid && (frmEmployee.submitted || Dob.touched)">Dob is required!</small>
- <small class="text-danger" *ngIf="Dob.valid && !IsMinDate">Date should be minimum 2019-01-01</small>
- <small class="text-danger" *ngIf="Dob.valid && !IsMaxDate">Date should be maximum 2025-01-01</small>
- </div>
- <div class="col-md-4 form-group" *ngIf="(ObjConfiguration.showmobile)">
- <label>Mobile</label>
- <input type="text" maxlength="10" class="form-control" [(ngModel)]="objEmp.PersonalDetails.Mobile" name="Mobile" id="Mobile"
- #Mobile="ngModel" pattern="^\d{10}$" required>
- <div *ngIf="Mobile.invalid && (frmEmployee.submitted || Mobile.touched)">
- <small class="text-danger" *ngIf="Mobile.errors.required">Mobile Number is required</small>
- <small class="text-danger" *ngIf="Mobile.errors.pattern">Mobile number must be 10 digits</small>
- </div>
- </div>
- <div class="col-md-4 form-group" *ngIf="(ObjConfiguration.showemail)">
- <label>Email ID</label>
- <input type="email" class="form-control" [(ngModel)]="objEmp.PersonalDetails.Email" name="Email" id="Email"
- #Email="ngModel" pattern="^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$" required>
- <div *ngIf="Email.invalid && (frmEmployee.submitted || Email.touched) ">
- <small class="text-danger" *ngIf="Email.errors.required">Email is required</small>
- <small class="text-danger" *ngIf="Email.errors.pattern">Email must be proper format like @ ,.com</small>
- </div>
- </div>
- <div class="col-md-4 form-group" *ngIf="(ObjConfiguration.showgender )">
- <label>Gender</label>
- <select name="Gender" class="form-control" #Gender="ngModel" [(ngModel)]="objEmp.PersonalDetails.Gender"
- required>
- <option *ngFor="let item of Genders" [value]="item">
- {{item}}
- </option>
- </select>
- <small class="text-danger" *ngIf="Gender.invalid && (Gender.touched || frmEmployee.submitted)">Gender is required</small>
- </div>
- </div>
- <hr class="line">
- <div class="row" *ngIf="(ObjConfiguration.showcommdetails)">
- <h5 class="ml-2 col-md-12 mb-3">
- <strong>Communication Details</strong>
- </h5>
- <div class="col-md-4 form-group" *ngIf="(ObjConfiguration.IsStreet)">
- <label>Street</label>
- <input type="text" class=" form-control text-uppercase" [(ngModel)]="objEmp.CommunicationDetails.Street" name="Street"
- id="Street" maxlength="50" #Street="ngModel" required>
- <small class="text-danger"
- *ngIf="Street.invalid && (Street.touched || frmEmployee.submitted) && ObjConfiguration.IscommMandatory">Street is required</small>
- </div>
- <div class="col-md-4 form-group" *ngIf="(ObjConfiguration.IsArea)" >
- <label>Area</label>
- <input type="text" class=" form-control text-uppercase" [(ngModel)]="objEmp.CommunicationDetails.Area" name="Area" id="Area"
- #Area="ngModel" maxlength="50" required>
- <small class="text-danger" *ngIf="Area.invalid && (Area.touched || frmEmployee.submitted) && ObjConfiguration.IscommMandatory">Area is
- required</small>
- </div>
- <div class="col-md-4 form-group " *ngIf="(ObjConfiguration.IsDistrict)" >
- <label>District</label>
- <input type="text" class="form-control text-uppercase" [(ngModel)]="objEmp.CommunicationDetails.District" name="District"
- id="District" maxlength="50" #District="ngModel" required>
- <small class="text-danger"
- *ngIf="District.invalid && (District.touched || frmEmployee.submitted) && ObjConfiguration.IscommMandatory">District is
- required</small>
- </div>
- <div class="col-md-4 form-group" *ngIf="(ObjConfiguration.IsState)">
- <label>State</label>
- <input type="text" class="form-control text-uppercase" [(ngModel)]="objEmp.CommunicationDetails.State" name="State"
- id="State" maxlength="50" #State="ngModel" required>
- <small class="text-danger" *ngIf="State.invalid && (State.touched || frmEmployee.submitted) && ObjConfiguration.IscommMandatory">State
- is required</small>
- </div>
- <div class="col-md-4 form-group" *ngIf="(ObjConfiguration.IsPincode)" >
- <label>Pincode</label>
- <input type="text" class=" form-control" [(ngModel)]="objEmp.CommunicationDetails.pincode" name="pincode"
- id="pincode" maxlength="6" #pincode="ngModel" required>
- <small class="text-danger"
- *ngIf="pincode.invalid && (pincode.touched || frmEmployee.submitted) && ObjConfiguration.IscommMandatory">pincode is required</small>
- </div>
- </div>
- <div class="text-right m-2 ">
- <button class="btn btn-primary " type="submit">Submit</button>
- <button class="btn btn-danger ml-2" style="float:right" type="reset">Reset</button>
- </div>
- </form>
- </div>
- </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.
- export class PersonalDetails {
- public Name: string;
- public Dob: string;
- public Mobile: string;
- public Email: string;
- public Gender: string;
- }
- export class CommunicationDetails {
- public Street: string;
- public Area: string;
- public District: string;
- public State: string;
- public pincode: string;
- }
- export class Employee {
- public PersonalDetails: PersonalDetails = new PersonalDetails();
- public CommunicationDetails: CommunicationDetails = new CommunicationDetails();
- }
- export class Configuration {
- public showcommdetails: boolean;
- public IsStreet: boolean;
- public IsArea: boolean;
- public IsDistrict: boolean;
- public IsState: boolean;
- public IsPincode: boolean;
- public showpersonalDetails: boolean;
- public Isname: boolean;
- public showname: olean;
- public showmobile: boolean;
- public showdob: boboolean;
- public showemail: boolean;
- public showgender: boolean;
- }
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.
- import {
- Component,
- OnInit
- } from '@angular/core';
- import {
- EmployeeService
- } from '../employee.service';
- import {
- Employee,
- Configuration
- } from 'src/employee';
- @Component({
- selector: 'app-employee',
- templateUrl: './employee.component.html',
- styleUrls: ['./employee.component.css']
- })
- export class EmployeeComponent implements OnInit {
- public showmode: string;
- public objEmp: Employee;
- public ObjConfiguration: Configuration;
- Genders = ['Male', 'Female'];
- constructor(private srvEmployee: EmployeeService) {
- this.showmode = 'Register';
- this.objEmp = new Employee();
- this.ObjConfiguration = new Configuration();
- }
- ngOnInit() {
- this.srvEmployee.getConfig().subscribe(data => this.ObjConfiguration = data);
- }
- }
The next step is to open the employee.service.ts file and replace the following code inside it as given below.
- import {
- Injectable
- } from '@angular/core';
- import {
- Employee,
- Configuration
- } from '../employee';
- import {
- HttpClient
- } from '@angular/common/http';
- import {
- Observable
- } from 'rxjs';
- @Injectable({
- providedIn: 'root'
- })
- export class EmployeeService {
- public Url = '/assets/config.json';
- constructor(private http: HttpClient) {}
- public getConfig(): Observable < Configuration > {
- return this.http.get < Configuration > (this.Url);
- }
- }
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.
- {
- "showcommdetails": true,
- "IsStreet": false,
- "IsArea": true,
- "IsDistrict": true,
- "IsState": true,
- "IsPincode": true,
- "showpersonalDetails": true,
- "Isname": true,
- "showname": true,
- "showdob": false,
- "showmobile": true,
- "showemail": true,
- "showgender": true
- }
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.