Oops! Looks like there's an issue with the type error: value.forEach is

I am working on creating an update form in Angular 6 using FormArray.

Below is the code snippet I have in editfrom.TS :

  
// Initialising FormArray
valueIngrident = new FormArray([]);

constructor(private brandService: BrandService, private PValueInfoService: ProductinfovalueService, private productinfoService: ProductinfoService, private catService: CategoryService, private produSrvice: ProductService, private route: ActivatedRoute, private fb: FormBuilder) {
    this.id = +this.route.snapshot.paramMap.get('id');
    this.productVM = this.produSrvice.InitialProduct();

}

ngOnInit() {

    this.InitialForm();
    this.GetMainCat();
}

InitialForm() {
    this.editFG = this.fb.group({
        productTitle: ['', Validators.compose([Validators.required])],
        productName: ['', Validators.compose([Validators.required])],
        color: ['', Validators.compose([Validators.required])],
        productImageName: ['', Validators.compose([Validators.required])],
        price: ['', Validators.compose([Validators.required])],
        gurantyMonth: ['', Validators.compose([Validators.required])],
        gurantyCompanyName: ['', Validators.compose([Validators.required])],
        catId: ['', Validators.compose([Validators.required])],
        brandId: ['', Validators.compose([Validators.required])],
        values: this.valueIngrident
    });
    this.GetProductByID(this.id);
}

public GetProductByID(id: number) {
    this.produSrvice.GetProductDetailById(id).subscribe((data) => {
        this.productVM = data;
        this.SelectBrand = data.brandId;
        this.SelectCat = data.catId;
        this.PName = this.productVM.productName;
        this.editFG.setValue({
            productTitle: [data.productTitle],
            productName: [data.productName],
            color: [data.color],
            productImageName: [data.productImageName],
            price: [data.price],
            gurantyMonth: [data.gurantyMonth],
            gurantyCompanyName: [data.gurantyCompanyName],
            catId: [data.catId],
            brandId: [data.brandId],
            values: this.valueIngrident
        });
        this.ChangeFormByType(data.catId);
    })
}

get ValueFormControl() {
    return this.editFG.get('values') as FormArray;
}

public CreateValueFiled(PD: Productinfovalue[]) {
    for (let element of PD) {
        this.valueIngrident.push(
            new FormGroup({
                infoId: new FormControl(element.infoId),
                value: new FormControl(element.value)
            })
        )
    }
}

public ChangeFormByType(id: number) {
    this.ChangeBrand(id);
    this.PValueInfoService.GetAllInfoValueForUpdate(id).subscribe(
        res => {
            this.PD = res,
            this.CreateValueFiled(this.PD)
        }
    )
}

And I use that in HTML :


<div class="form-inline lbin" formArrayName="values">
<div class="form-inline lbin" *ngFor="let valueCtrl of ValueFormControl.controls; let i=index" [formGroupName]="i">
    <div class="form-inline lbin">
        <label></label> 
        <input formControlName="value" >
    </div>
</div>
</div>

However, when the page loads, it shows me this Error :

ERROR TypeError: value.forEach is not a function at FormArray.push../node_modules/@angular/forms/fesm5/forms.js.FormArray.setValue (forms.js:3545)

What could be causing this issue?

Answer №1

FormArray's setValue function requires an array as the first parameter, but you are passing an object instead.

Take a look at your GetProductByID(id:number) function where you have this.editFG.setValue({...})

According to the official documentation:

setValue(value: any[], options: { onlySelf?: boolean; emitEvent?:boolean; } = {}): void Parameters value any[] Array of values for the controls

options object Configure options that determine how the control propagates changes and emits events after the value changes

onlySelf: When true, each change only affects this control, and not its parent. Default is false. emitEvent: When true or not supplied (the default), both the statusChanges and valueChanges observables emit events with the latest status and value when the control value is updated. When false, no events are emitted. The configuration options are passed to the updateValueAndValidity method. Optional. Default is {}.

Returns void

Your parameter is wrapped in "{}", indicating it is being treated as an object. However, the setValue function expects an array as specified by the documentation.

The issue arises because the setValue function attempts to use forEach on the parameter, which can only be done on arrays. This results in the error message "value.forEach is not a function."

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

Contrasting covariant and contravariant positions within Typescript

I'm currently diving into the examples provided in the Typescript advanced types handbook to broaden my understanding. According to the explanation: The next example showcases how having multiple potential values for the same type variable in co-var ...

Following the application of the filter function, a singular array was generated as the output

function sortByAge(arr) { let ageSorted = arr.sort(function(a, b) { return Object.fromEntries(a).age - Object.fromEntries(b).age }); // Arrange by young age. it's working well. let result = []; let names = ageSor ...

Issue with Docker setup for managing a PNPM monorepo

As a newcomer to Docker, I am attempting to configure my fullstack API REST project. Within my PNPM workspace, I have two applications - a frontend built with Angular and a backend developed using AdonisJS. My goal is to create a Docker configuration for P ...

Render doesn't wait for the componentWillMount lifecycle method

I'm currently working on implementing a redirection to the home page for logged-in users. I'm using ping to fetch login information, setting a state based on the response, and then checking that state in the render method for redirection. However ...

Sort through a list of objects by certain properties

I'm currently dealing with two arrays: one contains displayed columns and the other contains objects retrieved from a database, with more attributes than the displayed columns. displayedColumns = ['CompanyName','Ticker', 'Id& ...

Customize Bootstrap radio buttons to resemble standard buttons with added form validation styling

Is there a way to style radio buttons to look like normal buttons while maintaining their functionality and form validation? I have two radio buttons that need styling but should still behave like radio buttons. Additionally, I am utilizing Bootstrap for s ...

Guide on invoking a POST endpoint within another POST API in a Node.js Express server

I encountered an issue while attempting to use fetch in react.js with a backend node.js API URL, which then proceeds to make a POST API call within the server to another route utilizing a different URL. How can I tackle this task effectively? See the code ...

Divide Angular component unit test involving asynchronous tasks

One of my components is responsible for fetching data from a server using a service and then displaying it. I have created a test for this component which ensures that the data is loaded correctly: ... it('Should contain data after loading', as ...

How can we combine two phone calls and display the outcomes using typeahead ngx-bootstrap?

Let me walk you through the code that is currently working: <input [formControl]="search" [typeahead]="suggestions" typeaheadOptionField="name" (typeaheadOnSelect)="onSelectedDriver($event)&qu ...

Display HTML containing a <script> tag within a REACT component

Looking to embed the following HTML code within a React component: <form action="/process-payment" method="POST"> <script src="https://www.example.com/payment-script.js" data-preference-id="$$id$$"> </script> </form> I ...

Tips for swapping out an item mid-scrolling?

What is the best way to change the navbar when scrolling a page in React? How can I achieve this while following React's concepts? Is using getElementById considered bad practice? const useState = React.useState const useEffect = React.useEffect con ...

Simultaneously iterate through two recursive arrays (each containing another array) using JavaScript

I have two sets of arrays composed of objects, each of which may contain another set of arrays. How can I efficiently iterate through both arrays and compare them? interface items { name:string; subItems:items[]; value:string; } Array A=['parent1&ap ...

JavaScript and jQuery validation issues persisting

Here is the HTML code I am using: <script src="js/validate.js"></script> <label>FIRST NAME:</label> <td> <input type="text" class="firstname" id="firstname" onKeyUp="firstname()" /> </td> <td> <label id=" ...

Node.js application - varying NODE_ENV upon NPM launch

Operating my node.js application can be quite confusing. When launched by npm start, it operates in "production" mode, whereas when launched using node start.js, it runs in 'development' mode. I want to ensure that the 'development' mo ...

Organize intricate JavaScript Arrays

Similar Question: How to sort an array of javascript objects? I'm in the process of transitioning some of my older ActionScript 2.0 code to JavaScript. While most things are running smoothly, I've hit a roadblock when trying to numerically s ...

Storing array data locally within an AngularJS application for seamless sharing between two separate applications

I need assistance with persisting and sharing array data var queries = []; between two separate AngularJS applications. One application is for the front end, while the other is for the admin side. Both applications cause the entire page to load when access ...

What are some strategies for creating a website that caters to both web crawlers and users of single page applications?

Let's get down to the specifics. I've got a frontend website at (don't worry, it's not porn). If you have javascript enabled, the URL becomes [this uses jquery/ajax load]. If you're without javascript, the URL remains as . To ...

"Unlocking the power of AngularJS translate: A step-by-step

I'm seeking answers to two questions. 1) How can I utilize angularjs translate with ng-repeat? Although my Json file works fine, the text does not display when using ng-repeat. Here is a snippet from my json: "rules":{ "points":[ {"t ...

Angular Project: Exploring Classes and Interfaces with and without the Export Keyword

Currently, I am delving into the world of Angular. I have taken up a video course and also referred to a PDF book, but I find myself perplexed when it comes to understanding the usage of the "export" keyword... The PDF course focuses on Angular 5 and util ...

Unable to simulate a service and retrieve information in an angular unit test - showing as undefined

In my current project, I have a component that I am trying to write unit tests for. However, when I run the test, I noticed that the value of console.log('**fav**' + favorite[`isFavorite`]); shows up as undefined. This indicates that the data I ...