What is the best way to incorporate a formArray into a formGroup?

Before anything else, I want to apologize for any errors in my English.

I seem to be having trouble adding an array field to a formGroup.

My issue arises when attempting to use the push method to add a formArray to my rate formGroup. It appears that the error lies with the formControlName.

https://i.sstatic.net/O5nEm.png

Even after researching and reading about this issue, I am still unable to find a solution. Can anyone offer some assistance, please?

I have created a StackBlitz example to showcase the error I am encountering:

https://stackblitz.com/edit/angular-mlk2mh

Answer №1

In order to effectively utilize FormArray, it is important to grasp the following concepts:

                Mandatory form group
                   \/\/\/
<form [formGroup]="categories">
    <input type="text" placeholder="category_name" formControlName="category_name" />
                      Define form array
                          \/\/\/
    <div formArrayName="itemsList" *ngFor="let item of categories.get('itemsList').controls; let i = index;">
        <div [formGroupName]="i"> <-- crucial step
            <input type="text" placeholder="item_id" formControlName="item_id" />
            <input type="text" placeholder="Item Name" formControlName="item_name" />
            <input type="text" placeholder="Quantity" formControlName="quantity" />
        </div>
    </div>
</form>

To implement the above HTML structure in your TypeScript file, ensure you have:

categories: FormGroup;
itemsList: FormArray;

this.categories = this._formBuilder.group({
  category_name: [null, Validators.compose([Validators.required, Validators.minLength(5)])],
  itemsList: this._formBuilder.array([
    this._formBuilder.group({
      item_id: 0,
      item_name: '',
      quantity: 0,
    })
  ])
});

Lastly, create an addNew function:

addItem() {
   this.itemsList = this.categories.get('itemsList') as FormArray;
   this.itemsList.push(this.itemsList);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can you explain the significance of the symbol ! when declaring a variable in TypeScript?

Currently, I am delving into an Angular project and came across a peculiar line of code in the component.ts file provided by my instructor. @Input() public searchType!: string; This line resides within the OnInit() function of the component's TypeScr ...

NPM TypeORM is throwing the error message "Duplicate migrations" when changes are made to a migration file

Recently, I made a modification to an existing table by adding a new column using the command npm run migration:generate <filename>. Unfortunately, I realized later on that I had misspelled the column name and needed to correct it (showComission -&g ...

Identify matching values in objects and dynamically update them with a custom value

I have an array structured like this: var array = [ { dates: "2020-12-25", class: "first" }, { dates: "2020-12-26", class: "last" }, { dates: "2021-06-11", class: "first" }, ...

Rotating the camera around the origin in Three.js

Hey, I'm having some trouble with what I thought would be a simple task. I have a group of objects at the origin, and I'm trying to rotate a camera around them while always facing the origin. According to the documentation, this code should work: ...

Transforming a jQuery menu into an active selection with Vue JS

I am looking to transition away from using jQuery and instead utilize Vue for the front end of a menu. Specifically, I need to add an active class and a 'menu-open' state to the appropriate nested list items, similar to what is achieved in the pr ...

When making a GET request with Angular and NodeJS that includes parameters, only the response object is returned without any associated

Let's say I have a URL like 'localhost:3000/verify/a5d5sd', which I send to a user via email. When the user clicks on this link, I use the parameter (a5d5sd) in the link to check some conditions on the server and in my MongoDB database. The ...

Navigate to the following slide by clicking on BxSlider

Looking to enhance the navigation on my slideshow by using the slide itself as a next button, instead of relying on traditional prev/next controls. Although it seems like a simple feature to implement, I'm struggling to make it work. This is my curre ...

Troubleshooting: Discord bot failing to initialize on Heroku

After successfully hosting my bot on Heroku for a while, I temporarily switched back to self-hosting to update to discord.js v13. Now that I'm done with the updates and trying to re-host the bot on Heroku, I'm encountering this error: (node:4) Un ...

What is the process of integrating passportjs(node) API with the Angular cli?

After successfully configuring Node.js with PassportJS OAuth2, the need arose for Angular to call the Node API. However, they are running on different ports. While calling all of Node.js's REST APIs from Angular works fine using proxy.conf.json, an er ...

Using Angular to import a JSON file stored locally

I am facing an issue with importing a .json file in my Angular project. The file is located outside the project structure as shown below: | common | configuration.json | angular-app | src | app | my-component | ...

Error Encountered - Node.js application experiencing issues in passport login functionality

I'm in the process of developing a login application using nodejs and incorporating passport js for authentication. The app is connected to a local MySql database and utilizes sequelize as its ORM library. Within my user model, I've implemented ...

What strategies can be implemented to improve the load time for bigvideo.js?

Why are my load times extremely slow for such a small site? I had hoped to display an image before the video loads, but they both seem to load simultaneously, even if the video takes forever to load. This is my HTML: <div id="bigvid"> <div cla ...

From vanilla JavaScript to the powerful lodash library

Can you help me determine if these statements are equivalent? myApp.filter('myFilter', function() { var result, i, sport, y, contains, league; return function(sports, filterBy) { if (angular.isUndefined(sports) || !filterBy) { ...

I am currently utilizing react-admin, however, I am encountering an issue with the heavy build causing errors

Currently, I am working on developing the frontend using react-admin. Initially, I intended to utilize NextJS and found a helpful reference article. Reference: When attempting to run next dev, everything worked smoothly without any errors. However, when ...

Form submissions are not saving checkbox answers

As a beginner, I'm struggling to save the checkbox answers on the page after submission. The code below is quite lengthy (checkboxes start at 314). I have a feeling that I might be missing a piece of code, but I just can't seem to pinpoint what i ...

Having trouble with submitting the code - need help resolving the issue

I'm facing an issue with my submit cancel code. The JavaScript code I implemented for preventing the submission function on my page isn't working as expected. While it does work to a certain extent, it's not fully functional. I am seeking a ...

Pagination malfunction on AngularJS md-data-table is causing issues

I have been working on a project that involves retrieving data from an API and displaying it in a table. I am using AngularJS and the md-data-table library by Daniel Nagy. Following the setup instructions, I was able to display my data successfully. Howeve ...

Do I need to include success as a parameter in my Ajax call even if my function does not return any values?

When an image is clicked, I trigger an ajax call. The image includes an href tag that opens a different page in a new tab upon click. The purpose of this ajax call is to record the user's clicks on the image for telemetry purposes in a database table. ...

Using Waveskeeper for Verification: Solutions for Resolving the 'Waves is not defined' Issue

I'm currently working on creating a page that authenticates users with Waveskeeper. I have successfully installed the Waveskeeper addon on Chrome, but I keep encountering an error: ReferenceError: Waves is not defined. I've attempted to use both ...

Ensure that Ajax requests are successfully executed when a user navigates away from the page

I have developed an HTML/JavaScript application that requires an AJAX request to be made when the user refreshes or closes the page in order to close the application gracefully. To achieve this, I am using the pageunload event. I have implemented the func ...