FormArray.patchValue is throwing an error that states: "TypeError: value.forEach is not a function

Encountering the following error:

ERROR Error: Uncaught (in promise): TypeError: value.forEach is not a function
TypeError: value.forEach is not a function
    at FormArray.patchValue.

Fetching data from Laravel, aiming to display it in a FormArray.

The code in question:

this.http.get("http://data_dink" + '/' + event.value)
 .toPromise().then(data => 
 {
    console.log(data);
    this.getSelectedServiceData = data;
    console.log(this.getSelectedServiceData.service);
    this.addForm.get('services').patchValue(this.getSelectedServiceData.service);
 });

The data variable (response from get request) holds the following object:

{
   "msg":"Service Information",
   "service":{
      "id":1,
      "name":"Web Development",
      "description":"Test per web development",
      "price":"200.00",
      "created_at":"2020-05-04T03:07:28.000000Z",
      "updated_at":"2020-05-06T03:07:28.000000Z",
      "view_service":{
         "href":"api\/v1\/service\/1",
         "method":"GET"
      }
   }
}

Constructing a FormArray based on this object:

{
   "msg":"List of all services",
   "services":[
      {
         "id":1,
         "name":"Web Development",
         "description":"Test per web development",
         "price":"200.00",
         "created_at":"2020-05-04T03:07:28.000000Z",
         "updated_at":"2020-05-06T03:07:28.000000Z"
      },
      {
         "id":2,
         "name":"Java",
         "description":"test per java",
         "price":"100.00",
         "created_at":"2020-05-20T03:07:57.000000Z",
         "updated_at":"2020-05-20T03:07:57.000000Z"
      }
   ]
}

Answer №1

When using the manual for FormArray patchValue, it requires an array as its first argument:

patchValue(
  value:        any[], 
  options: { 
    onlySelf?:  boolean; 
    emitEvent?: boolean; 
  } = {}
): void

An error message indicates that the value argument needs to be in array format. To address this, wrap the argument for patchValue inside square brackets []:

The solution to your question would look like this:

this.addForm
      .get('services')
      .patchValue(
        [
          this.getSelectedServiceData.service
        ]
      )

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

A guide for implementing fast-json-patch in your Angular 2 projects

Looking to incorporate the "fast-json-patch" library into my Angular 2 project. This library can be found at https://github.com/Starcounter-Jack/JSON-Patch. I attempted to include the following code: 'fast-json-patch': 'vendor/fast-json-pa ...

Exploring the Augmented Theme in Material UI Using TypeScript and the "keyof" Operator

I've recently started working with TypeScript and I'm facing an issue that I can't seem to solve. Here's the problem: I extended my Material UI theme with the following types: declare module '@material-ui/core/styles/createPalette& ...

Extension for VS Code that displays the properties of a model

Is there a VS Code extension available that allows me to view the properties of a model directly from the HTML markup? For instance, when typing ngModel and then pressing the dot (.) key, it would display its properties similar to how it works in a TypeScr ...

Accessing a particular node in JSON using PHP's JSONPath function

Here is the structure of my JSON data: { "Photos":{ "Photo":[ { "ID" : 111, "type" : "JPEG", "URL": "blabla" }, { "ID": 222, ...

Issue with Angular Forms: Inability to type in field after using patchValue

I have a question regarding a form that I am toggling from a data-table. The issue is that when I use patchValue to pre-fill the form, it seems like I cannot edit the content of the field. Strangely enough, fields that are not filled with patchValue can be ...

How can I detect the shift key press when an array key is pressed in Angular 2?

I have a collection of items that I want to implement file traversal behavior for, similar to a file explorer. This means that after selecting an item, if you hold down the shift key and press the down arrow, those items should also be selected. Below is ...

Are the functions 'useEffect' and 'useCallback' being repetitively used in this case?

I have implemented a custom hook in my React application to manage back navigation actions (POP). The functionality is operational, but I can't help but notice that useCallback and useEffect seem to be performing similar tasks. Here is the snippet of ...

The Angular single-page application fails to refresh when being executed via Visual Studio 2017 Community

I have encountered a problem with my angular 6 app not refreshing when running through Visual Studio 2017. The project consists of multiple projects, including a .NET Core 2 WebAPI and the angular app in question. Even after setting the startup to only be ...

Encountering an error while utilizing ngForm in an HTML form

I have developed a custom component called "login", where I created an HTML form named "login.component.html". To convert this form into an Angular form, I added the code "" in login.component.html and imported import {NgForm} from '@angular/forms&apo ...

Is the Angular custom validator failing to trigger if the input is left untouched?

My form setup is as follows: this.form = this.formBuilder.group({ name: ['', Validators.required], email: ['', this.customValidator()] }); I have a button labeled "submit" with a condition for disabling: <button [disabled]=" ...

Using an API call within a lazy-loading function to restrict the amount of data received from the

I have implemented a project where I am restricting the API response to only show 5 items initially. Upon scrolling to the bottom of the page, I want to make another API call to fetch the next 2 items from the API. However, my current code only checks if ...

Struggling to develop a version of sequelize-auto. Encounter the error message: Unable to locate module './lib/auto' while attempting to execute a command within my project

I'm seeking forgiveness for my lack of experience in TypeScript. I must apologize in advance as I am unfamiliar with Sequelize-auto and need to replace repository and project names in code examples. My goal is to create a fork of Sequelize-auto to cu ...

PHP is unable to provide a JSON response

What could be causing a PHP file not to respond as JSON, while it responds correctly to the connected file? File Response Code <?php header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json; charset=UTF-8"); include '.. ...

Creating a JSON representation of a join-model along with its related models

Within my Rails application (version 4.1.5 / ruby 2.0.0p481 / win64), I've established a many-to-many relationship between Student and Course. This association is represented by a join model called StudentCourse, which includes an additional attribute ...

Can a substring within a string be customized by changing its color or converting it into a different HTML tag when it is defined as a string property?

Let's discuss a scenario where we have a React component that takes a string as a prop: interface MyProps { myInput: string; } export function MyComponent({ myInput }: MyProps) { ... return ( <div> {myInput} </div> ...

Tips for showing the parsed JSON data in a TableView using a TextField

Hello there, I am just starting out with iPhone development and need some guidance. I'm currently working on incorporating a webservice to fetch JSON response strings, parsing them using JSONvalue and displaying the parsed data on labels through butt ...

Are union types strictly enforced?

Is it expected for this to not work as intended? class Animal { } class Person { } type MyUnion = Number | Person; var list: Array<MyUnion> = [ "aaa", 2, new Animal() ]; // Is this supposed to fail? var x: MyUnion = "jjj"; // Should this actually ...

Troubleshooting the carouselExampleIndicators issue in Angular 4

I successfully implemented a carousel on my webpage using the code below: <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselExampleIndicat ...

Steps to automatically close a Bootstrap modal after redirection using RouterLink in Angular 6

Currently, I am working on my first Angular application. The issue I am facing involves a Bootstrap modal with a button that redirects to another section within the app. <button type="button" class="btn btn-info btn-lg" routerLink="/contactar">Cont ...

What is the most effective way to decode a JSON formatted multidimensional array of checkboxes?

Uncertain if the Title was accurate, the actual application is a quiz. Let me provide an example with this sample snippet. <form method="POST"> Softdrinks: <div class="checkbox"> <label><input type="checkbox" ...