Issue: While trying to add a new component to a formArray, the formGroup function requires an instance of FormGroup

I am currently implementing the Reactive Forms Approach in my project. Within a form (with the parent component named: DeductionInvoicesComponent), I have the following structure:

<form [formGroup]="deductionForm">
      <div formArrayName="items" class="well well-lg">
        <app-deduction-invoice-item
          *ngFor="let item of deductionForm.get('items')?.controls; let i=index"
          [index]="i"
          (removed)="deductionForm.get('items').removeAt($event)">
        </app-deduction-invoice-item>
      </div>
</form>
<button type="button" class="btn btn-primary" (click)="addItem()">Add an item</button>

The TypeScript code for the parent component is as follows:

export class DeductionInvoicesComponent implements OnInit {

  deductionForm: FormGroup;

  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.deductionForm = this.fb.group({
      items: this.fb.array([])
    });
  }

  addItem(){
    let control = <FormArray>this.deductionForm.controls.items;
    control.push(DeductionInvoiceItemComponent.buildItem());
  }
}

This form can have multiple instances of DeductionInvoiceItemComponents within a formArray. The child component (a single item named: DeductionInvoiceItemComponent) is structured as follows:

<div class="row" [formGroup]="item">
    <div class="form-group col-4">
      <label class="center-block">Title</label>
      <select class="form-control" formControlName="title">
        <option value="test">test</option>
      </select>
    </div>
    <div class="form-group col-4">
      <label class="center-block">Invoice Number</label>
  <input class="form-control" formControlName="invoiceNumber">
</div>
<button (click)="removed.emit(index)" type="button" class="close text-danger" aria-label="Close">
  <span aria-hidden="true">&times;</span>
</button>

Furthermore, the TypeScript code for the single component representing an item in the formArray is as follows:

export class DeductionInvoiceItemComponent {

  @Input()
  public index: number;

  @Input()
  public item: FormGroup;

  @Output()
  public removed: EventEmitter<number> = new EventEmitter<number>();

  static buildItem() {
    return new FormGroup({
      title: new FormControl('', Validators.required),
      invoiceNumber: new FormControl('', Validators.required),
      grossAmount: new FormControl('', Validators.required)
    });
  }
}

Upon clicking the addItem() button, I encounter the following error message:

Error: formGroup expects a FormGroup instance

I am creating the FormGroup using the static buildItem function as shown. How can I resolve this error?

Answer №1

Your DeductionInvoiceItemComponent should have the following code:

@Input()
  public item: FormGroup;

If you haven't already, make sure to pass it as an Input from the parent component by adding this line:

<app-deduction-invoice-item
          *ngFor="let item of deductionForm.get('items')?.controls; let i=index"
          [index]="i"
          [item]='item' // <-- ADD THIS LINE
          (removed)="deductionForm.get('items').removeAt($event)">
</app-deduction-invoice-item> 

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

Employing square bracket notation based on the input data

I'm currently in the process of enhancing some code within my library, but I've encountered a perplexing issue with bracket notation not functioning as expected when attempting to call an imported class. The parameter type expects a camelCased s ...

retrieve the router information from a location other than the router-outlet

I have set up my layout as shown below. I would like to have my components (each being a separate route) displayed inside mat-card-content. The issue arises when I try to dynamically change mat-card-title, as it is not within the router-outlet and does not ...

Inquiry on SSGHelpers and GetStaticProps functionality with parameterization

I am currently implementing createProxySSGHelpers to prefetch data using trpc in a project I'm developing, but I'm facing an issue where the id from the url params is returning as undefined even though it's visible in the url bar. Below is ...

Obtaining a value from within an Angular 'then' block

I have a unique issue that I haven't been able to find a solution for on StackOverflow: Within an Angular 6 service, I am trying to call a function from another service using TypeScript. Here is the code snippet: Service1: myArray: Array<IMyInte ...

Encountering a service error that results in the inability to read properties of undefined when passing a method as a

Whenever I attempt to pass a service function as a parameter to another function, an error 'Cannot read properties of undefined myService' occurs during execution. However, calling this.myService.method() individually works perfectly fine without ...

The utilization of `ngSwitch` in Angular for managing and displaying

I am brand new to Angular and I'm attempting to implement Form Validation within a SwitchCase scenario. In the SwitchCase 0, there is a form that I want to submit while simultaneously transitioning the view to SwitchCase 1. The Form Validation is fun ...

Generating a unique serial ID using Angular/JS

I am in the process of developing a function that will create a unique serial id by replacing a string with the format; xxxx-xxxx-xxxx-xxxx. The desired outcome is a serial like this: ABCD-1234-EFGH-5678, where the first and third parts consist of letters ...

Best practices for organizing API Services using TypeScript and Next.js Server Actions

My product-actions/index file contains various server actions such as createProduct and getProductAssets, each of which verifies the user session before processing the request. I am looking for a way to check the session validity only once and then procee ...

Sending asynchronous data to a child component in Angular 2

Having trouble with passing asynchronous data to a child component. I am attempting to create a dynamic form generator, but I encounter an issue when trying to fetch JSON data via an Observable and then passing it to the child component. Service: generat ...

Removing validators in Angular forms after submitting the form and resetting it

I am currently working on an Angular app that includes a form. Whenever I click the submit button, the reset() function gets triggered on the form. However, after the reset() function is called, all inputs are marked as having errors. I have tried using fu ...

Emotion, material-ui, and typescript may lead to excessively deep type instantiation that could potentially be infinite

I encountered an issue when styling a component imported from the Material-UI library using the styled API (@emotion/styled). Error:(19, 5) TS2589: Type instantiation is excessively deep and possibly infinite. Despite attempting to downgrade to typescript ...

Can you explain the significance of the 'project' within the parserOptions in the .eslintrc.js file?

Initially, I struggle with speaking English. Apologies for the inconvenience :( Currently, I am using ESLint in Visual Studio Code and delving into studying Nest.js. I find it difficult to grasp the 'project' setting within the parserOptions sec ...

Troubleshooting: Socket.io integration in Angular is not functioning within a .then() statement

Upon running this code snippet in a component: const videoholder = <HTMLDivElement>( document.querySelector('#videoholder') ); const myPeer = new Peer(this.userid, { host: '/', ...

Error TS2339: The attribute 'scope' is not found in the 'JwtPayload' data type

Encountering an error in my IntelliJ IDE while trying to utilize decodedJwt.scope. The specific error message reads: Property 'scope' is not available on type 'JwtPayload'. Suggestions offered by IntelliJ include: sub, aud, exp, iat, ...

Typescript and Apollo Client return types intertwined

My goal is to create a simple function within a class that generates an Apollo Client. Below is the code I have implemented: import appConfig from 'config/app-config'; import { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/clie ...

Typescript throws an error when Redux useSelector fails to properly infer the state

Seeking guidance on how to access my state using the useSelector hook import { applyMiddleware, createStore } from 'redux'; import thunk from 'redux-thunk'; import { reducers } from './reducers'; export c ...

Are push notifications supported in Ionic3?

I've been struggling to set up push notifications in my Ionic3 app for the past couple of days, and no matter what I try, it doesn't seem to work due to the current versions I'm using. Here are my current versions: rxjs: 5.5.11 Angular: 5 ...

Building upon the foundation: Extending a base component in Angular

I have a Base Component that is extended by its children in Angular. However, when creating a new Component using angular-cli, it generates html and css files that I do not need for the base component. Is there a way to create a Base Component without inc ...

Frequent occurrence when a variable is utilized prior to being assigned

I am currently working with a module import pino, { Logger } from 'pino'; let logger: Logger; if (process.env.NODE_ENV === 'production') { const dest = pino.extreme(); logger = pino(dest); } if (process.env.NODE_ENV === &apo ...

Angular 7 - Issue with Loading Material Component Styles

In the midst of my latest Angular 7 project, I decided to incorporate the out-of-the-box material components. Unfortunately, there seems to be a hiccup with some of the CSS not being applied and pinpointing the cause is proving to be an elusive task. For ...