Dynamically Managing Elements in Angular

Angular, a robust platform for building web applications, offers a plethora of features to streamline the development process. One of its most intriguing capabilities is the dynamic manipulation of form elements. In this guide, we delve deeper into this topic, exploring how to dynamically add and manage form controls using Angular's Reactive Forms.

Understanding Angular’s FormArray

In the realm of Angular's Reactive Forms, every form is represented by a model, which can be crafted using the FormControl and FormGroup APIs. For those who prefer a more succinct approach, the FormBuilder API is a viable alternative.

Picture a scenario where a form's structure and controls are determined based on user interactions or data fetched from a backend service. Such forms, which can be modified on-the-fly, are termed as dynamic forms. A quintessential example is an in-place editable form where users can seamlessly add or delete rows, each comprising multiple editable controls.

To cater to such dynamic requirements, Angular introduces the FormArray API. Here's a quick rundown of its most frequently used methods:

  • controls: An array encompassing all the controls within the array.
  • length: Represents the total number of controls in the array.
  • at(index): Retrieves the form control located at the specified array index.
  • push(control): Appends a new control to the array's end.
  • removeAt(index): Excludes a control from the specified array position.
  • getRawValue(): Fetches the values of all form controls.

Crafting a Dynamic Angular Form

To commence, we must first establish a reactive form. This involves integrating the FormBuilder API into our component:

TypeScript
constructor(private fb: FormBuilder) {}

Subsequently, we can define a form with three distinct fields: email, password, and roles.

TypeScript
form = this.fb.group({
    email: ['', { validators: [Validators.required, Validators.email] }],
    password: ['', [Validators.required, Validators.minLength(8)]],
    roles: this.fb.array([]),
});

The roles field, being a FormArray, will facilitate the dynamic addition or removal of controls.

To efficiently manage this FormArray, we can devise a getter function:

TypeScript
get rolesFieldAsFormArray(): any {
    return this.form.get('roles') as FormArray;
}

This getter will be instrumental in our HTML template to dynamically render newly added fields and manage control operations.

To dynamically introduce controls, we can define a method:

TypeScript
role(): any {
    return this.fb.group({
      role: this.fb.control(''),
    });
}

This method returns a FormGroup with a singular role control.

Adding Controls to the FormArray

To infuse new controls into our roles FormArray, we can employ the following method:

TypeScript
addControl(): void {
    this.rolesFieldAsFormArray.push(this.role());
}

Removing Controls from the FormArray

Conversely, to eliminate controls, the subsequent method proves useful:

TypeScript
remove(i: number): void {
    this.rolesFieldAsFormArray.removeAt(i);
}

Upon integrating these functionalities, our dynamic form is primed for user interactions.

HTML Representation

The HTML structure for our dynamic form is as follows:

HTML
<form [formGroup]="form">
    <!-- ... other form controls ... -->
    <div *ngFor="let control of rolesFieldAsFormArray.controls; let i = index;" formArrayName='roles'>
        <div [formGroupName]="i">
            <div class="input-field">
                <input matInput type="text" placeholder="Role" formControlName="role">
            </div>
            <button class="button" type="button" (click)="remove(i)">Remove</button>
        </div>
    </div>
    <button class="button" (click)="addControl()"> Add New Role</button>
    <!-- ... other form controls ... -->
</form>

Conclusion

Dynamic forms in Angular, powered by the FormArray API, offer unparalleled flexibility in managing form controls. Whether it's crafting forms based on backend data or allowing users to modify form structures, Angular's Reactive Forms provide the tools necessary for a seamless experience.

By harnessing the power of the FormArray API, developers can create intuitive, dynamic forms that cater to diverse requirements, ensuring a user-friendly interface and streamlined data management.

FAQs

  • What is FormArray in Angular?
    • FormArray is an API in Angular's Reactive Forms that allows for the dynamic addition and removal of form controls.
  • How can I dynamically add controls to my form?
    • By utilizing the push method of the FormArray, you can dynamically append new controls to your form.
  • Can I remove controls from my form dynamically?
    • Yes, using the removeAt method of the FormArray, you can specify the index of the control you wish to remove.

Author