Oops! Looks like you forgot to provide a value for the form control named <name>. Make sure to fill

I have encountered an issue with a nested operation. The process involves removing an offer and then saving it again as a repeating one.

However, the problem arises when I try to use patchValue() on the item in offerList[index] after saving the repeating offer. An error occurs:

Error: Must supply a value for form control with name: 'id'.

Upon debugging, everything seems to be in order. The object saved in the final subscription contains valid fields. The id is present and not null:

this._offerService.remove(this.placeId, offer)
  .pipe(
    flatMap((removed: OfferModel) => {
      removed.id = null;
      removed.repeatWeekly = true;
      return this._offerService.save(this.placeId, removed)
        .pipe(finalize(() => this.updateOffersFormArray()));
    }),
  )
  .subscribe(
    (saved) => {
      console.log(saved);
      offerList[index].patchValue(saved);
    });

The console will display:

{id: 55, offerDate: "2019-03-04", …}

In the function updateOffersFormArray(), this error occurs:

// this.offersFormArray is a FormArray
updateOffersFormArray() {
  const tmp = this.repeatingOffers.concat(this.offers);
  console.log(tmp);
  this.offersFormArray.setValue(tmp); // <-- Throws error
}

The console output shows an array of FormGroup elements as expected. Each element's value includes an offer with all values set, including id, which contradicts the error message.

I'm struggling to identify the issue despite spending considerable time on it.

Although the code may seem unconventional, executing updateOffersFormArray() triggers a status change event in this.offersFormArray. This event updates this.offers and this.repeatingOffers for display purposes. Here is the related code:

this.offersFormArray.statusChanges.subscribe((e) => {
  const offers: Array<AbstractControl> = [];
  const repeatingOffers: Array<AbstractControl> = [];

  for (const k of Object.keys(this.offersFormArray.controls)) {
    const offerForm = this.offersFormArray.controls[k];
    const offer = <OfferModel> offerForm.value;

    if (offer.repeatWeekly) {
      repeatingOffers.push(offerForm);
    } else {
      offers.push(offerForm);
    }
  }

  this.offers = offers;
  this.repeatingOffers = repeatingOffers;
});

Answer №1

It turns out my initial understanding of using setValue() for the FormArray was incorrect. Instead of accepting a list of AbstractControl, it actually requires values that match the structure of the control.

All I needed to do was make this adjustment:

this.offersFormArray.setValue(tmp); 

to:

this.offersFormArray.setValue(tmp.map(control => control.value));

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

Challenges with overwriting TailwindCSS classes within a React component library package

I just released my very first React component on NPM. It's a unique slider with fractions that can be easily dragged. Check it out here: Fractional Range Slider NPM This slider was created using TailwindCSS. During bundling, all the necessary classe ...

Limiting the use of TypeScript ambient declarations to designated files such as those with the extension *.spec.ts

In my Jest setupTests file, I define several global identifiers such as "global.sinon = sinon". However, when typing these in ambient declarations, they apply to all files, not just the *.spec.ts files where the setupTests file is included. In the past, ...

Fixed headers remain in place as you scroll horizontally on a single table

Within my system, I have organized two tables: table one and table 2 are stacked on top of each other. I've managed to freeze the column headers so that they are displayed vertically, remaining static as users scroll horizontally. To achieve this effe ...

Steps for updating the clientId and authority values in MSAL configuration after they have already been read

Currently, I am utilizing Azure AD B2C for a multi-tenant application. The user starts by inputting their email, followed by selecting an option from a drop-down list populated based on the tenant they are associated with (tenant1, tenant2, tenant3). If th ...

Exporting symbols within the same namespace from multiple files in a TypeScript project

I have a typescript module and I am looking to define symbols within the 'aaa' namespace from multiple files. Here is an example of what my code looks like: a.ts: export namespace aaa { export const a = "a"; } b.ts: export namespac ...

Guide on creating a Meteor Bootstrap WhatsApp clone

I'm currently going through the step-by-step guide for Whatsapp on the following website: After entering this command: meteor npm install angular@^1.5.8 --save I encountered the following message: no matches found: angular@^1.5.8 Does this mean t ...

Creating a new Angular2 component for a separate URL path

In my scenario, I have a PageComponent that gets refreshed with new data when the URL changes (using PageService). It currently utilizes the same PageComponent object, but I am looking to make it a new object when the URL changes. 1st Question: How can ...

The instanceof operator does not recognize the value as an instance and is returning false, even though it

Is there a method to verify the current instance being used? This is what I am logging to the console: import { OrthographicCamera } from 'three'; // Later in the file: console.log(camera instanceof OrthographicCamera, camera); and the result ...

The directive within the module was not carried out

After setting up a fresh module in my Angular 8 project and adding a new directive to it, nothing seemed to happen at runtime (although the compilation was successful). I even added console logs to the directive to check if it was being executed different ...

Retrieving the Final Value from an Observable in Angular 8

Is there a way to retrieve the most recent value from an Observable in Angular 8? let test = new BehaviorSubject<any>(''); test.next(this.AddressObservable); let lastValue = test.subscribe(data=>console.log(data.value)); Despite my ef ...

Having trouble getting a constructor to function properly when passing a parameter in

Here's the code snippet I'm working with: import {Component, OnInit} from '@angular/core'; import {FirebaseListObservable, FirebaseObjectObservable, AngularFireDatabase} from 'angularfire2/database-deprecated'; import {Item} ...

Adding onBlur validation for radio buttons and checkboxes in Angular Material UI

Currently, I am working on implementing checkboxes and radio buttons using Angular Material UI. My main issue lies in achieving the desired red outline effect when a required field is left unselected by the user. Even after applying the necessary 'req ...

Step-by-step guide on importing CSS into TypeScript

I have a global CSS file where I've defined all the colors. I attempted to import that value into TypeScript but it didn't work. This is my latest attempt: get sideWindowStyle(): any { switch (this.windowStyle) { case 'classicStyl ...

Converting an array of objects to an array based on an interface

I'm currently facing an issue with assigning an array of objects to an interface-based array. Here is the current implementation in my item.ts interface: export interface IItem { id: number, text: string, members: any } In the item.component.ts ...

Is it possible to transfer files using Angular 2?

Currently, I am utilizing Angular2 and TypeScript to transmit a file in conjunction with JSON Data to a designated server. HTML Code <input type="file" class="form-control" name="avatar" id="uploadyour" name="uploadyour" #uploadyour="ngModel" [(ngMode ...

Is there a way for me to generate an Nx command that can dynamically create a library with a specified name?

In the world of Nx and Angular, I have a repository named org housing all my projects. To create a special library within this setup, like one called auth, I typically use a command that looks like this: npx nx g @nx/angular:lib auth-data-access --directo ...

What is the best way to trigger an event from a child component to a parent component in

parent.component.ts public test(){ //some code..... } parent.component.html <app-child (eventfire)="test($event)"></app-child> In this scenario, the child component button is displayed within the parent component. However, there i ...

Issue: (SystemJS) the exports variable is not defined

In the process of developing a .net core mvc + angular application, I encountered an interesting situation. The MVC framework handles user management, and Angular takes over when users navigate to specific areas of the application. Initially, I integrated ...

`In NestJS Nested Schema, the @Prop decorator and mongoose options are not applied as expected

I'm currently working on constructing a Schema that includes a nested object. I am trying to define default values and required properties within the nested object, but it seems like the options I set are being ignored. task.entity.ts @Schema() expor ...

Creating a parameterized default route in Angular 2

These are the routes I've set up: import {RouteDefinition} from '@angular/router-deprecated'; import {HomeComponent} from './home/home.component'; import {TodolistComponent} from './todolist/todolist.component'; import { ...