Passing an Angular 6 FormArray as an array

I've implemented Reactive Forms on my website using FormBuilder.

There are two fields in the form with FormControls, and also an array of user-created fields stored in a FormArray.

The issue arises when sending data to the server - instead of sending the array as is, the FormArray sends a string with items listed out separated by commas.

How can I ensure that the data sent to the server retains its array format?

Below are the methods defined in my class:

formGroup = this.fb.group({
    link: [null, [
      Validators.required,
      Validators.pattern(/^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$/)
    ]],
    image: [null, Validators.required],
    features: this.fb.array([this.fb.control('', Validators.required)])
  });

beforeSubmit(): FormData {
    const formData = new FormData();

    formData.append('link', this.link.value);
    formData.append('image', this.image.value);
    formData.append('features', this.features.value);

    return formData;
  }

  submit() {
    console.log('submit');

    const formData = this.beforeSubmit() as FormData;

    this.ss.postSite(formData).subscribe(
      response => {
        console.log(response);
      }
    );

  }

As for the service:

postSite(input: FormData) {
    console.log('posting');

    return this.http.post<Site>(this.API_URL, input, this.HEADERS).pipe(
      catchError(this.handleError)
    );
  }

Answer №1

Resolved

this.features.value has been replaced with

this.features.getRawValue().forEach(element => {
  formData.append('features[]', element);
});

This allows us to iterate through arrays of rawValues.

Answer №2

The issue is not related to FormArray, but rather with FormData mapping arrays to strings. Consider implementing this alternative approach:

submit() {
   console.log('submit');
   const formData = this.formGroup.value;

   this.ss.postSite(formData).subscribe(
     response => {
       console.log(response);
     }
   );

 }

Remember to use FormData specifically when sending files using <input type="file" />.

Answer №3

A FormArray groups together the values of all child FormControls into an array

In order to populate a FormArray with FormControls based on user input, you need to push them accordingly. If you have already implemented this functionality, please provide the corresponding code snippet

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

"The functionality for detecting changes in an Electron application has ceased to work after implementing zone.js version 0.9.1

Recently, I took over an Electron app originally built with Angular 6 and decided to update it to Angular 8. After following all the upgrade guides, I managed to get everything up and running smoothly - or so I thought. It wasn't until I started inter ...

Developing a Navigation Bar Menu using JSON data and the power of Lodash

Seeking advice to enhance my code for creating a navbar menu from JSON data. Any suggestions on how to avoid calling getItems multiple times? Appreciate any feedback, thank you! var _ = require('lodash'); let menuConfig = [ { ID: 1 ...

Ways to prevent the use of the JavaScript increment (++) or decrement (--)

I have created two functions for a multi-step configuration on a webpage. protected clickNext(event:any, config:any) : any{ this.activeIndex++; } protected clickPrev(event:any, config:any) : any{ this.activeIndex--; } Here are the buttons: < ...

Is there a way to verify if a component contains a child node with the tag <template></template>?

Consider the scenario with MyComponent: <div [my-component]="'text'"></div> Within the code, I have access to this.viewContainerRef, which refers to the DOM node itself (<div>). However, for customization purposes, a user mig ...

What is the best way to create an object with a generic mapped type?

My defined mapped type looks like this: type FooOrBar = "foo" | "bar" type ObjectWithHi<T extends FooOrBar> = { [key in T]: 'hi'; } I am trying to create a function call that follows this structure: getFooOrBa ...

The function `$('body').on('blur')` is having issues in Internet Explorer 8

How can I fire a function when $('body').on('blur') occurs? This code works perfectly in all browsers except for IE8 $(document).ready(function () { $(window).focus(); $(window).on("focus", function () { ...

Using Node.js: Only bring in the necessary function, don't execute the entire file

Today, I stumbled upon an interesting observation and I'm curious about the peculiar behavior of node in this scenario. I have two files structured as follows: src/api/index-api.ts src/worker/index-worker.ts Both of these files contain a simple con ...

Having difficulty retrieving a JSON Object value through an angular2 pipe

I am currently working on creating a dynamic table using Angular2. I have set up an Angular2 component with two pipes: the first pipe successfully retrieves the key from the JSON object, which is used as the column for the table. However, the second pipe, ...

Unable to render a rectangle with React's canvas context.fillRect

Could anyone help me with drawing a rectangle using React? I'm having trouble getting it to work. I'm confused as to why the code below isn't showing a rectangle on the screen. class DrawingView{ constructor(props) { this.canva ...

Updating the content in an HTML document using jQuery

In my workflow, I am utilizing jquery ajax to retrieve information from a PHP file. data = <option>Peter</option><option>Maria</option> Following that, I aim to leverage jquery to insert this data after the initial option. <s ...

Decoding a JSON object in node.js

{"__v":0,"_id":{"$oid":"55f13d34258687e0bb9e4385"},"admin":true,"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b3d6ded2c3dfd682f3d4ded2dadf9dd0dcde">[email protected]</a>","last_login":"11:25:24 AM","name ...

Error message: A boolean type cannot be used as a function in the fullcalendar ajax call

I have successfully implemented a fullcalendar into my app and have added a method to filter results by user: function filterEventsByProvider(selected_provider) { $('#calendar').fullCalendar('removeEvents'); $('#calendar&a ...

Struggling to retrieve the values of dynamically generated input fields using a combination of ajax and php

I'm attempting to utilize an Ajax function to post values obtained from a form. Initially, I'm using another Ajax function to populate the form's text box. Then, in order to submit the form data, I'm trying to implement another Ajax fun ...

Conflicting Angular controller names within different modules

I'm facing an issue where two modules (A and B) with controllers of the same name are conflicting when imported into module C. Is there a recommended solution to prevent this conflict, such as using a naming convention like "module.controller" for ea ...

Prevent any delay between two video segments

Revised after being placed on hold My objective is to seamlessly play video files back-to-back without any transitions. Due to limitations on the Raspberry Pi, I am currently using omxplayer to achieve this. I have chosen to write my code in node.js as i ...

Checking URL validity using JavaScript Regex

I attempted to validate a URL with or without the http protocol, but no matter what I tried, the function kept returning false. I verified my regex string on this website: And it appeared as expected. function isUrlValid(userInput) { var rege ...

Custom Angular component experiencing issues with displaying pre-selected options

I'm currently working on a component with a multi-select dropdown feature. The goal is to be able to provide a list of objects (specifically ICatagory in my case) for the options when creating an instance of this component. Additionally, I want to pas ...

How to Use Multiple Arrays in jQuery to Find ChildNodes Based on Class Attribute in HTML?

I manage my weekly schedule manually through a static table. <table> <tr class="live al tv"> <td>October 2</td> <td>12:30 pm</td> <td class="competition"></td> <td>Team A v Team B< ...

How can PrimeNG PIE chart values be displayed by default instead of only on hover over the slice?

front end <td> <div class="p-col-8 ui-toolbar-group-right"> <button pButton type="button" icon="pi pi-search" (click)="populate_charts()"></button> </div> </td> TS-File ...

The v-show directive is not activated by a Vuex commit

I am experimenting with vuex for the first time, and I have come across an issue where a v-show directive is not triggering after a mutation commit on the store. // store.js import Vue from "vue" import Vuex from "vuex" const states = ...