whatsapp_btn
whatsapp_btn Chat With Us

Home >> AngularJS >> Types of Angular Forms and How to Develop Dynamic Forms?

Types of Angular Forms and How to Develop Dynamic Forms?

  8 min read
Types of Angular Forms and how to develop dynamic forms

Types of forms in Angular

Types Of Formes In Angular
  1. Dynamic forms: Reactive forms that allow for the dynamic development of form fields are known as Angular dynamic forms. Angular dynamic form builder is an angular plugin that create form dynamically using JSON. When the number of form fields is unknown in advance or when the form fields depend on other user inputs, this is helpful. In this blog, we will learn about dynamic forms in Angular.

  2. Model-driven forms: Reactive forms, sometimes referred to as Model-driven forms, are trickier to use than template-driven forms. They are more adaptable and scalable than template-driven forms since they are defined programmatically using TypeScript classes. Dynamic form fields, form validation, and personalized form controls are characteristics that reactive forms offer.

  3. Template-driven forms: The simplest and most popular kind of forms in Angular are template-driven forms. They are referred to as template-driven because directives like ngForm, ngModel, and ngSubmit are used to define the form structure within the template itself. These forms are simple to put up, but they are best used for straightforward use cases or small-scale projects because of their limited versatility.

What is the dynamic forms?

What is the dynamic form
  • An approach to constructing forms that can be generated dynamically based on user input or other conditions is the dynamic form in Angular. Building a form component that can render various fields and sections depending on the data it receives is required. This method is helpful when the form’s structure has to change in response to user activity, such as when new form fields need to be added or removed or when users need to choose which portions to display. Complex forms can be more easily created and require less code to maintain, thanks to the dynamic form technique.

What justifies the use of the dynamic forms?

What Justifies The Use of the Dynamix Form

Angular’s dynamic form is utilized for generating forms that can be created dynamically based on user input or other conditions. There are different types of forms in Angular and here you can see some of the main reasons why you should think about building dynamic forms in Angular. There are various reasons for using dynamic forms in Angular:

  • dynamic forms are flexible and simple to alter to meet application requirements. Based on user settings and other factors, they can show various fields.
  • When an application expands, adding or removing form fields is simple and doesn’t require modifying the structure of the form component.
  • Because dynamic forms eliminate redundant code, developers can reuse them to construct many forms with various fields and sections.
  • dynamic forms provide a better user experience by adapting to the user’s input and showing or hiding fields and sections accordingly.

Generally, employing dynamic forms increases form creation flexibility and scalability, making it simpler to develop complex forms and manage them over time.

Want to hire AngularJs Developers for your next project?

Looking for reliable and experienced AngularJS developers to help you build your next project? Look no further. Our team of experts is ready to work with you. Contact us today to get started.


How can we create dynamic forms?

If you are wondering how to create dynamic form in Angular then don’t worry here you can see how developers can create dynamic forms angular.

Step 1:-

Create one folder in your shared folder module like the folder name is form_controller. In this form_controller folder, we need to create three files (form_genrator, form_fileds, form_parameters ).

  • form_genrator :- In this file we need to write the code to generate a dynamic form.
import { Validators } from '@angular/forms';
import { template_ref } from './fields'


export const generateForm = (fields: any) => {
   let group: any = {};
   fields.forEach((field: string) => {
       let f = template_ref[field]
       let validations = [];
       if(f.required){
           validations.push(Validators.required)
       }
       if(f.emailRequired){
           validations.push(Validators.email)
       }


       if(f.pattern){
           validations.push(Validators.pattern(f.pattern))
       }
      
       group[field] = [f.defaultValue || '', validations]; 
   });
   return group
}
  • form_fileds :- In this file, we need to declare the form name/formGroupName and form fields/formControlName name.
export const segment = {
   userForm: {
       fields: [
           'name',
           'lName',
           'mobile'
       ]
   }
}
  • form_parameters :- In this file we need to declare the required fields.
export const template_ref: any = {
   name: {
       label: 'Name',
       controlType: 'text',
       placeholder: 'Enter your name',
       autofillOff: true,
       required: true
   },
   lName: {
       label: 'Last Name',
       controlType: 'text',
       placeholder: 'Enter your last name',
       autofillOff: true,
       required: true,
       pattern: /^(\+91[\-\s]?)?[0]?(91)?[789]\d{9}$/g
   },
   mobile: {
       label: 'Mobile No',
       controlType: 'number',
       placeholder: 'Enter Your mobile no',
       autofillOff: true,
       required: true
   }
}

Step 2:

  • Create a component in the shared folder module. For creating dynamic input tags with different different types.

input.component.html

<div [formGroup]="form" [ngSwitch]="fieldObj.controlType">
 <ng-container *ngSwitchCase="fieldObj.controlType === 'radio'">
   <div class="form-check" *ngFor="let g of fieldObj.options">
     <input class="form-check-input" type="radio" name="gender" [value]="g" [formControlName]="key" />
     <label class="form-check-label" [for]="key">
       {{ g }}
     </label>
   </div>
 </ng-container>
 <div class="dropdown" *ngSwitchCase="fieldObj.controlType === 'dropdown'">
   <label [for]="key">{{ fieldObj.label }}</label>
   <button class="btn btn-light dropdown-toggle" type="button" (click)="openDropdown = !openDropdown">
     {{form.get(key)?.value || 'Select City'}}
   </button>
   <div class="dropdown-menu" [ngClass]="{show: openDropdown}" aria-labelledby="dropdownMenuButton">
     <ng-container *ngFor="let el of fieldObj.options">
       <a class="dropdown-item" (click)="onSelectDropdown(el.name)">{{ el.name }}</a>
     </ng-container>
   </div>
 </div>
 <div class="form-group" *ngSwitchCase="fieldObj.controlType === 'textarea'">
   <label [for]="key">{{ fieldObj.label }}</label>
   <textarea [name]="key" [id]="key" cols="30" rows="3" class="form-control" [formControlName]="key"></textarea>
   <div class="help-box" *ngIf="isInValid">
     <p *ngIf="control && control.errors && control.errors['required']">Please enter Address.</p>
   </div>
 </div>
 <div class="form-group" *ngSwitchCase="fieldObj.controlType === 'fileUploader'">
   <label for="exampleFormControlFile1">Example file input: </label>
   <input type="file" class="form-control-file" id="exampleFormControlFile1" (change)="handleFileInput($event)">
 </div>
 <div class="form-group" *ngSwitchCase="fieldObj.controlType === 'dateTimePicker'">
   <label class="mr-3" [for]="key">{{ fieldObj.label }}</label>
   <ngx-datepicker [formControlName]="key" [options]="options"></ngx-datepicker>
 </div>
 <div class="form-group" *ngSwitchDefault>
   <label [for]="key">{{ fieldObj.label }}</label>
   <input [type]="fieldObj.controlType" class="form-control" [id]="key" [formControlName]="key"
     [placeholder]="fieldObj.placeholder || ''" [autocomplete]="fieldObj.autofillOff ? 'off' : 'on'" />
   <div class="help-box" *ngIf="isInValid">
     <p *ngIf="control && control.errors && control.errors['required']">{{ fieldObj.label }} is required!</p>
     <p *ngIf="control && control.errors && control.errors['email']">Please enter valid email ID!</p>
     <p *ngIf="control && control.errors && control.errors['pattern']">Please enter valid mobile number.</p>
   </div>
 </div>
</div>

input.component.ts

import { Component, Input, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { template_ref } from '../form_controller/form_parameters';


@Component({
 selector: 'app-input',
 templateUrl: './input.component.html',
 styleUrls: ['./input.component.scss']
})
export class InputComponent implements OnInit {


 @Input() form: FormGroup = new FormGroup({});
 @Input() key!: string;
 constructor() { }


 ngOnInit(): void {
 }


 get fieldObj() {
   return template_ref[this.key];
 }


 get fControl(){
   return this.form.controls;
 }
}

Step 3:-

  • Create a component to show your form. Now, You just need to use <app-input> to create an input tag. Like, I have a created component with the name dynamic-form.

dynamic-form.component.html

<div class="row d-flex justify-content-center mt-5">
   <div class="col-sm-6">
       <ng-container *ngFor="let field of fieldArray">
           <app-input [form]="formGroup" [key]="field"></app-input>
       </ng-container>
       <div class="btn btn-primary mt-2" (click)="getFormValue()">Save</div>
   </div>
</div>

dynamic-form.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { segment } from 'src/app/shared/form_controller/form_fileds';
import { generateForm } from 'src/app/shared/form_controller/form_genrator';


@Component({
 selector: 'app-dynamic-from',
 templateUrl: './dynamic-from.component.html',
 styleUrls: ['./dynamic-from.component.scss']
})
export class DynamicFromComponent implements OnInit {


 public formGroup: FormGroup = new FormGroup({});
 public form = segment['userForm'].fields;
 public fieldArray:any = [];
 constructor(private fb:FormBuilder) { }


 ngOnInit(): void {
 }
 ngAfterContentInit() {
   var fieldArray = generateForm(this.form);
   for (const field of Object.keys(fieldArray)) {
     this.fieldArray.push(field);
   }
   this.formGroup = this.fb.group(fieldArray);
 }


 public getFormValue(){
   console.log('this.formGroup.value :>> ', this.formGroup.value);
 }


}

Our Output:- 

Our Output

Conclusion

Dynamic form is the best approach to work with complex and huge-size forms, it can be expandable easily in the future if required. With the help of Angular form dynamic, developers can create grouped input controls. Hope that you learned how to build dynamic angular forms. Developers prefer to use Angular to create dynamic forms because Angular performance is good. Also, dynamic forms have many advantages, including the capability to add customization and validation choices, which makes them a preferred choice for dealing with complicated forms. Hire AngularJs developers if you are trying to get a fully featured solution that includes dynamic forms.

FAQ’S:

Yes, you can implement both forms in the same application. But to add Template-Driven and Reactive Forms in the same application you need to make sure that you import the modules simultaneously.

Reactive Forms are better and many developers prefer to choose them over Template-driven Forms because Reactive forms are more powerful and easier to be used.

Yes, you can easily use third party libraries like Angular Material to create different types of dynamic forms in Angular. There are many third-party libraries available in the market that can be implemented to create forms in angular.

Tagline Infotech
Tagline Infotech a well-known provider of IT services, is deeply committed to assisting other IT professionals in all facets of the industry. We continuously provide comprehensive and high-quality content and products that give customers a strategic edge and assist them in improving, expanding, and taking their business to new heights by using the power of technology. You may also find us on LinkedIn, Instagram, Facebook and Twitter.

Related Posts :

contact-us-bg

Our Global Presence

India

Surat (HQ)

Digital Valley, 423, Apple Square, beside Lajamni Chowk, Mota Varachha, Surat, Gujarat 394101

Ahmedabad

D-401, titanium city center, 100 feet anand nagar road, Ahmedabad-380015

 +91 9913 808 285

U.S.A

1133 Sampley Ln Leander, Texas, 78641

United Kingdom

52 Godalming Avenue, wallington, London - SM6 8NW

U.A.E

Office No - 43-44, Al Fahidi, Bur Dubai, Dubai, United Arab Emirates

 +971 58 569 4786