DEV Community

preetha S S
preetha S S

Posted on

ANGULAR DYNAMIC FORMS

What is dynamic forms in angular ?- The most asked interview question

In simple terms, dynamic forms mean that the form field configuration comes from the backend as a JSON response. On the frontend, we simply read this configuration and render the form dynamically with minimal code.
Lets see how we can achieve this

First let me clarify Reactive forms include static form field declaration which means you will need to declare each field and use the same in fromGroup but here as the fields come from JSON you just need to dynamically handle the fields in formGroup.

.ts file

`export class DynamicFormComponent implements OnInit {

  form!: FormGroup;
//json from BE
  fields = [
    { type: 'text', name: 'firstName', label: 'First Name', required: true },
    { type: 'email', name: 'email', label: 'Email', required: true },
    { type: 'number', name: 'age', label: 'Age', required: false }
  ];

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    const group: any = {};

    this.fields.forEach(field => {
      group[field.name] = field.required
        ? ['', Validators.required]
        : [''];
    });

    this.form = this.fb.group(group);
  }`
Enter fullscreen mode Exit fullscreen mode

.html file

`  <div *ngFor="let field of fields">
    <label>{{ field.label }}</label>

    <input
      [type]="field.type"
      [formControlName]="field.name"
    />

    <div *ngIf="form.get(field.name)?.invalid && form.get(field.name)?.touched">
      {{ field.label }} is required
    </div>
  </div>
Enter fullscreen mode Exit fullscreen mode

`

Top comments (0)