utilizing formArray of formGroup for mat-select within an angular application

I am currently working on a project where I require a material select box that allows for multiple values to be selected. These values are retrieved from an API that returns an array of objects. My goal is to generate a formarray of formgroups whenever a user selects a value from the select box.

For example:

The select box contains a list of categories, each represented by a category object. When a category is selected, I want the form to create a formarray consisting of the selected category object.

.html:

<div formArrayName="category">
  <div *ngFor="let x of myForm.get('category')['controls'];let i = index">
    <div [formGroupName]="i">
      <mat-form-field appearance="outline">
        <mat-label>Category</mat-label>
        <mat-select [formControlName]="name" multiple>
          <mat-option [value]="category.name"
          *ngFor="let category of categories">
          {{category.name}}
          </mat-option>
        </mat-select>
        <!--
          <mat-error *ngIf="myForm.controls.category.touched && myForm.controls.category.invalid">
                  <span *ngIf="myForm.controls.category.errors.required">Please select category</span>
          </mat-error>-->
      </mat-form-field>
    </div>
  </div>
</div>

.ts :

  category:this.fb.array([this.fb.group({
        "name":['']
      })]),

When a value is selected, the current output looks like this

category: Array(1)
   0:
     name: Array(2)
        0: "Finance & Economics"
        1: "Data Science"

However, I would like the output to be structured as follows:

category: Array(1)
   0:
     name: Array(2)
        0: "Finance & Economics"
   1:
     name: Array(2)
        0: "Data Science"

If anyone could assist me in resolving this issue, I would greatly appreciate it.

Answer №1

is

<div *ngFor="let x of myForm.get('category').controls;let i = index">

It is recommended to use a getter instead, as Angular may throw an error in production.

get categoriesArray()
{
    return this.myForm.get('category') as FormArray
}
//And use

<div *ngFor="let x of categoriesArray.controls;let i = index">

Also, remember that formControlName should not have [ or ].

<mat-select formControlName="name" multiple>

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

What is the best way to have react-bootstrap's Dropdown automatically open when hovering your mouse over it?

Looking for a simple solution. I want the dropdown to open when hovering over it, rather than clicking on it. Here is my current code: <Nav> <NavDropdown onMouseEnter = {()=> isOpen=true} open={isOpen} noCare ...

Utilize Symfony filtering alongside AJAX functionality with the added feature of the KnpPaginatorBundle

When filtering data using ajax, I encounter an issue with pagination in Symfony and KnpPaginatorBundle. The pagination works fine when displaying the data without any filters. However, after applying a filter using ajax, clicking on page 2 of the paginati ...

Having trouble sending the code through post message

I was trying to send some code to a node application using Postman with a POST message. In the body, I included the following code: module.exports = function() { var express = require('express'), app = express(); app.set('po ...

Unable to update to the most recent version of React-Bootstrap

I'm facing an issue while trying to upgrade to the newest version of react-bootstrap. When I run: npm install --save react-bootstrap The following message appears: npm notice created a lockfile as package-lock.json. You should commit this file. npm ...

Determine the overall price of the items in the shopping cart and automatically show it at the bottom without the need for manual entry

Creating a checkout form that displays the total cost of products, subtotal, GST cost, delivery cost, and overall price. The goal is to calculate the total by adding together the costs of all products with the "price" class (may need ids) at a 15% increase ...

What is the preferred method for updating a variable value - Ajax or PHP?

I'm in the process of creating a dropdown survey for new visitors using cookies to collect data, but I'm a bit confused on how to implement it. If a button is clicked, the onClick event will trigger var answer1 = answer1 + 1 , or something simil ...

In JavaScript, the addition and subtraction buttons may become disabled after nested lists are used

Recently, I embarked on a project to enhance the functionality of restaurant table items and implement value-saving features. Initially, everything worked smoothly with one item list. However, upon introducing a second list and attempting to manipulate it ...

Setting up the Node.js file system for an Ionic project: A step-by-step guide

Seeking a solution to delete a Folder/File on the client side using javascript/jQuery/AngularJS1. After researching, I found that it can be done using Node.js as shown in this Sitepoint link. Now, I am unsure how to integrate Node.js fs(File System) with ...

Selecting options on hover, either A or B at the least

I need a jQuery selector to handle an 'either' scenario. Specifically, I have a dropdown menu and want it to stay open when the user hovers over either of two elements. Either when they hover over the button or when they leave the popped-out men ...

eliminate the gap in the MUI Accordion when it is expanded

How can I prevent the Accordion MUI component from moving and applying top and bottom margins to summary elements in expanded mode? I added the following code to the summary element but it doesn't seem to be working. Any suggestions on how to fix this ...

Choosing only those elements that are not children of parents with a specific class by utilizing the `.not()` method

I am attempting to target all elements having the class .select that are nested somewhere within the DOM tree. The only condition is that these elements should not have any ancestors with the class .forbidden. This means it will not detect any elements ...

"Troubleshooting Nextjs in a Production Environment: Tips for Resolving Local Debugging Issues When

Everything is working flawlessly in my nextjs development setup. The build process goes smoothly without any issues. However, when attempting to serve the production locally, an error pops up saying: "Error: Element type is invalid: expected a string (for ...

Unidentified function error triggered by jQuery when clicked

Having trouble accessing a function defined by my colleague for a click event. The code snippet provided below is causing issues, any ideas on what could be wrong? function Start(data) { this.move= function() { .... }; $('.button').click( ...

router.query is returning an empty object when using Next.js

Here is how my folders are organized: https://i.stack.imgur.com/TfBtv.png In addition, here is a snippet of my code: const router = useRouter(); const { id } = router.query; The issue I'm facing is that the id is returning {} instead of the actual ...

To retrieve data from an AJAX response, you will receive an array in the form of a string

After requesting a list of posts submitted by users from my server, the response I received was a string containing an array of stdClass objects. If it had been an actual array, that would not have been an issue. However, it arrives as a string in the foll ...

Automatically tapping the Quora "expand" button through code

I am attempting to automate the clicking of the "more" button located at the bottom of a page like using watir. Below is the code I currently have: require 'watir-webdriver' b = Watir::Browser.new b.goto 'quora.com/'+ ARGV[2] + ' ...

Reasons for storing `https.get()` inside a request constant in Node.js

When using simple javascript, any content written to the console is displayed on the console itself. An example would be as follows: const name = "david"; This will display david in the console. However, in Node.js, if I store a request in a const varia ...

Implementing Checkbox Functionality within a Dropdown Menu using AngularJS or JavaScript

I am interested in finding a multi-select checkbox solution similar to the one demonstrated here: Instead of using jQuery, I would prefer options in AngularJS or pure JavaScript. Does such a solution already exist in these frameworks, or is there guidance ...

``There Seems to be an Issue with Loading Content in Tabs

Hey! I'm encountering an issue with my jquery tabs. The first tab content loads fine, but when I select another tab, the content doesn't display. Then, when I try to go back to the first tab, it doesn't load either. Here's the HTML cod ...

`<div>` element with a class of "button" that listens for

I've been attempting to use a userscript to automate a button click. Inspecting the element reveals the button code as: <div class="q-w-btn cl"></div> Unfortunately, the button lacks an id attribute, making it difficult for me to select ...