WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Angular · Advanced · question 45 of 100

How do you create and work with dynamic forms in Angular?

📕 Buy this interview preparation book: 100 Angular questions & answers — PDF + EPUB for $5

Creating and working with dynamic forms in Angular usually involves a combination of the following concepts:

1. Reactive Forms

2. FormGroups and FormArrays

3. FormBuilder

In this explanation, I’ll guide you through setting up a dynamic form that allows you to add and remove fields dynamically.

**Step 1: Setting up the form**

First, you need to initiate your Angular project and import the ‘ReactiveFormsModule‘ in your ‘app.module.ts‘ file:

import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports: [ReactiveFormsModule],
})
export class AppModule {}

**Step 2: Creating the form**

In your component’s TypeScript file, import these classes and create a form:

import { FormBuilder, FormGroup, Validators, FormArray } from '@angular/forms';

export class AppComponent implements OnInit {
  myForm: FormGroup;

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.myForm = this.fb.group({
      fields: this.fb.array([]),
    });
  }
}

Here, we are using ‘FormBuilder‘ to create a form with a ‘FormArray‘ named ‘fields‘. We will use this array to hold our dynamic form fields.

**Step 3: Create methods to add and remove form fields**

Now, let’s create methods to add and remove fields to/from the form:

addField() {
  const fieldGroup = this.fb.group({
    name: ['', Validators.required],
    value: ['', Validators.required],
  });
  this.fieldsArray.push(fieldGroup);
}

removeField(index: number) {
  this.fieldsArray.removeAt(index);
}

get fieldsArray() {
  return this.myForm.get('fields') as FormArray;
}

‘addField()‘ creates a new ‘FormGroup‘ containing two form controls (’name’ and ’value’). It then adds this field group to the ‘fieldsArray‘. ‘removeField()‘ removes the form group at a specified index from the ‘fieldsArray‘.

**Step 4: Create the form UI**

Finally, let’s create the HTML to represent this dynamic form:

<form [formGroup]="myForm">
  <div formArrayName="fields">
    <div *ngFor="let field of fieldsArray.controls; let i=index" [formGroupName]="i">
      <label>Name:</label>
      <input formControlName="name" placeholder="Field name">
      <label>Value:</label>
      <input formControlName="value" placeholder="Field value">
      <button (click)="removeField(i)">Remove</button>
    </div>
  </div>
  <button (click)="addField()">Add field</button>
</form>

This form shows our ‘fieldsArray‘ and iterates over its ‘FormGroups‘ using ‘*ngFor‘. It binds the form controls to the ‘name‘ and ‘value‘ inputs and uses the ‘removeField()‘ method to remove fields. The ‘addField()‘ method is called when the "Add field" button is clicked.

Now you have a dynamic form that allows you to add and remove fields. You can further customize the form by adding more controls or modifying the validation logic.

Remember to handle form submission in your component and process the form data as needed.

Here’s a sample submission handler:

onSubmit() {
  if (this.myForm.invalid) {
    alert('Please fill all required fields');
    return;
  }

  const formData = this.myForm.getRawValue();
  console.log('Form data:', formData);
}

And add a submit button to your form HTML:

<button (click)="onSubmit()">Submit</button>
Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Angular interview — then scores it.
📞 Practice Angular — free 15 min
📕 Buy this interview preparation book: 100 Angular questions & answers — PDF + EPUB for $5

All 100 Angular questions · All topics