Top Node.js Development Companies in India
November 15, 2024
Home >> AngularJS >> Types of Angular Forms and How to Develop Dynamic Forms?
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:
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.
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.
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 ).
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
}
export const segment = {
userForm: {
fields: [
'name',
'lName',
'mobile'
]
}
}
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
}
}
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;
}
}
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);
}
}
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.
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.
Digital Valley, 423, Apple Square, beside Lajamni Chowk, Mota Varachha, Surat, Gujarat 394101
D-401, titanium city center, 100 feet anand nagar road, Ahmedabad-380015
+91 9913 808 2851133 Sampley Ln Leander, Texas, 78641
52 Godalming Avenue, wallington, London - SM6 8NW