Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Dynamically Adding Form Controls in Angular

Dynamically adding form controls in Angular allows you to create flexible forms where the number of controls can change based on user interaction. This tutorial covers the basics of dynamically adding form controls effectively in your Angular applications.

Why Dynamically Add Form Controls?

Dynamically adding form controls is useful in scenarios where the number of input fields cannot be predetermined. Examples include adding multiple phone numbers, addresses, or other repeating sections of a form.

Setting Up Dynamic Form Controls

To dynamically add form controls, you need to set up your form with FormArray and use methods to add and remove controls:

// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, ReactiveFormsModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

// app.component.ts
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  userForm: FormGroup;

  constructor(private fb: FormBuilder) {
    this.userForm = this.fb.group({
      name: ['', Validators.required],
      email: ['', [Validators.required, Validators.email]],
      phones: this.fb.array([
        this.fb.control('', Validators.required)
      ])
    });
  }

  get phones() {
    return this.userForm.get('phones') as FormArray;
  }

  addPhone() {
    this.phones.push(this.fb.control('', Validators.required));
  }

  removePhone(index: number) {
    this.phones.removeAt(index);
  }

  onSubmit() {
    console.log('Form submitted!', this.userForm.value);
  }
}

// app.component.html
<form [formGroup]="userForm" (ngSubmit)="onSubmit()">
  <div>
    <label for="name">Name</label>
    <input type="text" id="name" formControlName="name">
    <div *ngIf="userForm.get('name').invalid && userForm.get('name').touched">
      <div *ngIf="userForm.get('name').errors.required">Name is required</div>
    </div>
  </div>
  <div>
    <label for="email">Email</label>
    <input type="email" id="email" formControlName="email">
    <div *ngIf="userForm.get('email').invalid && userForm.get('email').touched">
      <div *ngIf="userForm.get('email').errors.required">Email is required</div>
      <div *ngIf="userForm.get('email').errors.email">Invalid email format</div>
    </div>
  </div>
  <div formArrayName="phones">
    <div *ngFor="let phone of phones.controls; let i = index">
      <label for="phone{{i}}">Phone {{i + 1}}</label>
      <input type="text" [formControlName]="i" id="phone{{i}}">
      <div *ngIf="phone.invalid && phone.touched">
        <div *ngIf="phone.errors.required">Phone number is required</div>
      </div>
      <button type="button" (click)="removePhone(i)">Remove</button>
    </div>
    <button type="button" (click)="addPhone()">Add Phone</button>
  </div>
  <button type="submit" [disabled]="userForm.invalid">Submit</button>
</form>

Key Points

  • Dynamically adding form controls allows for flexible forms where the number of input fields can change based on user interaction.
  • Use FormArray to manage an array of form controls.
  • Methods such as push and removeAt are used to add and remove controls from a form array.
  • Display validation messages conditionally based on the form control's state.

Conclusion

Dynamically adding form controls in Angular provides a powerful way to handle forms with varying numbers of input fields. By understanding and using dynamic form controls effectively, you can create flexible and user-friendly forms in your Angular applications. Happy coding!