I am experiencing difficulties in assigning values to a formArray

I am struggling to update values in an array form, as I am facing challenges setting new values.

Although I attempted to set values using patch value, my attempts were unsuccessful.

// Component.ts
this.packageForm = this.formBuilder.group({
  title: ['', Validators.required],
  productImage: ['', Validators.required],
  price: ['', Validators.required],
  products: this.formBuilder.array([
    this.addProductFormGroup()
  ])
})

// Form Builder Array
addProductFormGroup(): FormGroup {
 return this.formBuilder.group({
  productNames: ['',Validators.required],
  productQuantities: ['',Validators.required]
})
}

 // Add Row
addProductsRow() 
{
 (<FormArray>this.packageForm.get('products'))
 .push(this.addProductFormGroup();
}

// Remove Row
 removeProductsRow(productGroupIndex: number) {  
 (<FormArray>this.packageForm.get('products'))
 .removeAt(productGroupIndex);
}

addPackage() {
this.productNames=null;
this.productQuantities=null;
this.packageForm.value.products.forEach(element => {
  this.productNames = (this.productNames == null) ? element.productNames 
   : this.productNames + "~" + element.productNames;
   this.productQuantities = (this.productQuantities == null) ? 
  element.productQuantities : this.productQuantities + "~" + 
   element.productQuantities;
  });
}

When triggering the click event addPackage(), I retrieve values from the form. My goal is to format and send the form data with productNames as [oil~sugar~flour] and productQuantity as [4~3~5].

Answer №2

Check out this solution:

  function addProductPackage() {
    const productNames = [];
    const productQuantities = [];

    this.packageForm.value.products.forEach(item => {
      productNames.push(item.productNames);
      productQuantities.push(item.productQuantities);
    });

    return {
      productNames: '[' + productNames.join('~') + ']',
      productQuantities: '[' + productQuantities.join('~') + ']'
    };
  }

Within your onSubmit function, construct a new object to send to the backend API. Here's an example:

function onSubmit() {
    const obj = addProductPackage();

    console.log(obj.productNames);
    console.log(obj.productQuantities);

    const dataToSend = {
      ...obj,
      title: this.packageForm.controls.title.value,
      price: this.packageForm.controls.price.value
    };

    // Send this data object to the backend API
    console.log(dataToSend)

  }

Check out Stackblitz for a working demo.

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

Utilizing ActivatedRoute in conjunction with another Service

I am facing an issue while trying to utilize the ActivatedRoute service in a different service. The problem lies in the fact that when I use the ActivatedRoute service in my service, it is observing the main App component and not picking up any route param ...

Comparing the use of Angular with Node.js and Nginx

Simply a question on my mind. In terms of benefits, which would be more advantageous: running my angular application through node with nginx as a reverse proxy or serving it directly from nginx? My intuition tells me that direct server from nginx would r ...

I am facing an issue with my ngmodel as it is not refreshing and the binding seems to

Currently, I am working with Ionic code and processing an image obtained through photo capture. While everything seems to be functioning correctly and I receive the blob data, the image is not displaying in the template. It appears that the Angular binding ...

Customizing font color upon hover in Next.js and Tailwind.css

Recently, I developed a Navbar component that displays a purple link when navigating to pages like Home or Projects. The issue arises when the background color is light; in this case, the link turns green on hover instead of staying purple. How would I adj ...

Position your content on the right side of the Angular Material tabs

I'm struggling with positioning content next to the tabs on the right side. I attempted placing content in a disabled mat-tab, but I don't want the content (located on the right) to be disabled. In addition, the content includes a dropdown menu ...

Encountering a 404 Error in Angular 17 When Refreshing the Page

After completing my Angular 17 project and deploying it to hosting, I encountered an issue where pressing F5 on the page would redirect me to a 404 error page. Despite searching for solutions, I was unable to resolve this situation within Angular 17. I am ...

What is the best way to deliver a file in Go if the URL does not correspond to any defined pattern?

I am in the process of developing a Single Page Application using Angular 2 and Go. When it comes to routing in Angular, I have encountered an issue. For example, if I visit http://example.com/, Go serves me the index.html file as intended with this code: ...

Utilize Angular 9 to fetch data from an API using the Get method, map them to a class, and

Seeking to extract information from a test URL and convert the data into a list, I aim to exhibit them in an alert/Loop for testing purposes. The dummy API URL being used is: The returned data follows this structure: {"status":"success","data":[{"id":"1" ...

Expanding the Warnings of React.Component

When I create a new class by extending React.Component in the following manner: export default class App extends React.Component<any, any > { constructor (props: React.ReactPropTypes) { super(props); } // other code } I encountere ...

The specified 'Object' type does not match the required 'Document' constraint

I need assistance with running a MERN application to check for any issues, but I keep encountering this error across multiple files. Error: The 'CatalogType' type does not meet the requirements of 'Document'. The 'CatalogType&apo ...

Can someone provide guidance on integrating UI components with Angular 8?

I have developed my own custom component called app-button.ts. This component is responsible for checking the current user's roles and rendering the button only if it matches the defined roles. The ButtonType property is used to specify the style of ...

The custom error page in NextJS is failing to display

In my custom pages/404.ts file, I have coded the following: export default function NotFound() { return <h1>404 - Page Not Found</h1> } Additionally, there is another page that displays a 404 error when the organization is null: import Error ...

Discovering the best way to utilize pagination for searching all data within Angular 8

Hey there, good morning everyone! I'm currently working on an Angular 8 app that showcases a table filled with data from a database. This table comes equipped with a search box and a pagination feature using the "Ng2SearchPipeModule" and "JwPaginatio ...

Standing alone, an argument can never be fully validated without

Recently, while delving into the valuable resource titled Effective TypeScript by Dan Vanderkam, I stumbled across an intriguing scenario that left me puzzled. Within a code snippet presented in the book, there was a line - shape; that seemed perplexing ...

What is the best way to align text alongside icons using ng-bootstrap in Angular 8?

I have a set of four icons positioned next to each other, but I want them to be evenly spaced apart. I tried using the justify-content-between class, but it didn't work. How can I achieve this? I'm creating a Progressive Web App (PWA) for mobile ...

Optimal Angular Project Structure for Creating an App with Admin Backend

After finishing "ng-book: The complete book on Angular 6," I am diving into Angular as a newcomer. As I venture into building my application, I have a specific question that has been lingering in my mind. The vision for my project includes: MainLayout: ...

Retrieve the interface property following the execution of the HTTP GET service

Having trouble accessing the array properties from my JSON file using the http get service. The goal is to display the Widget array on the web. service.ts: import { Http, Response, Headers } from '@angular/http'; import { Observable } from &apo ...

Using the Async feature, I can retrieve the value of a string type when the return type of a function is Promise<any>

While working on a custom pipe, I encountered a situation that puzzled me. Can you explain why the code snippet below is considered valid? async transform(value: any): Promise<string> { let fullNameBasedOnPreference: string; fullNameBasedOnP ...

React Bootstrap Forms: The <Form.Control.Feedback> element is failing to display when the validation is set to false

Problem: I am facing difficulties with displaying the React Bootstrap <Form.Control.Feedback></Form.Control.Feedback> when the validation is false in my form implementation. Steps to Recreate: Upon clicking the Send Verification Code button, ...

Can HTML be transferred between browser tabs using Angular?

I'm in the process of developing a unique Angular (v17) application that allows users to drag and drop HTML elements, even across multiple browser tabs. I am inspired by the capabilities demonstrated by neo.mjs, as shown in this demo: https://www.yout ...