Search⌘ K
AI Features

Modifying Forms Dynamically

Explore how to dynamically modify Angular forms by using FormArray to handle multiple form controls, and implement a CartService to manage shopping cart data. Learn to bind form controls to a list of products, update quantities, and display cart items with reactive forms. This lesson helps you build interactive, data-driven forms in Angular applications.

We’ll learn how to programmatically set values in a form. So far, we have used the FormGroup and FormControl classes extensively throughout this chapter. However, we have not seen what FormArray is all about.

Consider the scenario where we have added some products to the shopping cart of our e-shop application and want to update their quantities before checking out the order.

Adding a shopping cart service

Currently, our application doesn’t have any functionality for a shopping cart, so we will now add one:

  1. Create a new service to manage the shopping cart by running the following Angular CLI command in the src\app\cart folder:

Note: The command below is for creating a service locally using the Angular CLI.

ng generate service cart
Command to create a service
  1. Open the cart.service.ts file and add the following import statement:

import { Product } from '../products/product';
Importing the Product file
  1. Create a cart property in the CartService class and ...