Form input fields cannot be edited when formGroupName is being utilized

Setting up the form control:

formMain = this.fb.group({ 
  details: this.fb.array([
    new FormGroup({
      label: new FormControl(''),
      description: new FormControl(''),
    })
  ])
});

The HTML includes dynamic input fields:

<div formArrayName="details">
  <div *ngFor="let detail of formMain.value.details; index as i">
    <mat-form-field appearance="fill">
      <mat-label>Label of a detail</mat-label>
      <input id="detail-label" matInput type="text" [value]="detail.label">
    </mat-form-field>

    <mat-form-field appearance="fill">
      <mat-label>Description of a detail</mat-label>
      <input id="detail-description" matInput type="text" [value]="detail.description">
    </mat-form-field>
  </div>
</div>

Initially works correctly, but when attempting to edit values in the input fields, they are not stored in the form control. This could be due to missing formControlName.

To rectify, formControlName and [formGroupName]="i" were added:

<div *ngFor="let detail of formMain.value.details; index as i" [formGroupName]="i">
  <mat-form-field appearance="fill">
    <mat-label>Label of a detail</mat-label>
    <input id="detail-label" matInput type="text" [value]="detail.label" formControlName="label">
  </mat-form-field>
...

After making these changes, the input fields become uneditable. Upon inspection of the DOM, it seems that [formGroupName]="i" is causing the issue.

<div class="mat-form-field-infix ng-tns-c97-1030"><input _ngcontent-lqv-c198="" id="detail-label" matinput="" type="text" formcontrolname="label" class="mat-input-element mat-form-field-autofill-control ng-tns-c97-1030 ng-untouched ng-pristine ng-valid cdk-text-field-autofill-monitored" ng-reflect-name="label" ng-reflect-id="detail-label" ng-reflect-type="text" ng-reflect-value="Brooklyn" aria-invalid="false" aria-required="false"><span class="mat-form-field-label-wrapper ng-tns-c97-1030"><label class="mat-form-field-label ng-tns-c97-1030 ng-star-inserted" ng-reflect-disabled="true" id="mat-form-field-label-2045" ng-reflect-ng-switch="true" for="detail-label" aria-owns="detail-label"><!--bindings={
  "ng-reflect-ng-switch-case": "false"
}--><mat-label _ngcontent-lqv-c198="" class="ng-tns-c97-1030 ng-star-inserted">Label of a detail</mat-label><!--bindings={
  "ng-reflect-ng-switch-case": "true"
}--><!--bindings={
  "ng-reflect-ng-if": "false"
}--></label><!--bindings={
  "ng-reflect-ng-if": "true"
}--></span></div>

When removing [formGroupName]="i", the input field values can be edited but an error is encountered:

ERROR Error: Cannot find control with path: 'details -> label'

A solution to this issue is sought.

Answer №1

To enhance efficiency, it is advisable to iterate through the form controls of the details FormArray instead of directly accessing objects in the details array within the *ngFor loop.

Furthermore, there is no need to include the [value] attribute as the input field will automatically bind to the value when utilizing the formControlName attribute.

<div
  *ngFor="let detail of detailsFormArray.controls; index as i"
  [formGroupName]="i"
>
  <mat-form-field appearance="fill">
    <mat-label>Label of a detail</mat-label>
    <input id="detail-label" matInput type="text" formControlName="label" />
  </mat-form-field>

  <mat-form-field appearance="fill">
    <mat-label>Description of a detail</mat-label>
    <input
      id="detail-description"
      matInput
      type="text"
      formControlName="description"
    />
  </mat-form-field>
</div>
get detailsFormArray() {
  return this.formMain.controls.details as FormArray;
}

Check out the live demo on StackBlitz

For more information, refer to: Comprehensive Guide on Angular FormArray

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

Retrieve data that resets to undefined upon reloading from an array

Encountering an unusual error while working with TypeScript for the first time. Initially, when I use console.log(data), it displays an array with objects. However, upon reloading the webpage without making any changes, the console log shows undefined. con ...

In which location can one find the compiled TypeScript files within an Angular 2 project?

As a newcomer to learning Angular 2, I've come across tutorials that mention all compiled files should go into the dist folder. These compiled files refer to typescript files transpiled into JavaScript. However, upon creating my project using Angular ...

Encountered an unexpected interpolation ({{}}) in column 3 of Data Bind RouterLink (Angular 2) that was expecting an expression

Encountering difficulties passing data to my routerLink. The goal is to change the route when the id reaches 4 within the ngFor loop. <input type="button" class="btn-cards" [ngClass]="getStyle(negociacao)" [routerLink]="['/{{negociacao.rota}}&apo ...

Can we replace node_module imports with a different module (e.g. swapping lodash with lodash-es)?

Currently in the process of upgrading from angular 9 to angular 10 within my mono-repo. Encountering numerous warnings like the ones below: WARNING in \libs\global-search\src\lib\components\status\status.component.ts depe ...

TypeScript's type casting will fail if one mandatory interface property is missing while an additional property is present

While running tsc locally on an example file named example.ts, I encountered some unexpected behavior. In particular, when I created the object onePropMissing and omitted the property c which is not optional according to the interface definition, I did not ...

Is there a way to delete a wrapper (parent element) in Angular without deleting the child element as well?

The solution provided in this answer on Stack Overflow addresses jQuery and not Angular or TypeScript. My inquiry bears resemblance to this question raised on a forum, but I am specifically looking for a resolution within the context of Angular. Is there ...

Angular - Implementing *ngFor for nested table rows

I am currently working with an object that has a specific data structure: - title - id - [artists] - { artist obj / document , - [albums] - { album obj / document }, - { - album obj / document ...

Validation error occurs after submitting and resetting an Angular 6 form

In my Angular 6 app, I have a form with input fields and a button. When the button is clicked, the form data is displayed above the form and form.reset() is called to reset the form. However, after the form reset, the input fields turn red due to them bein ...

What is the process for server-side rendering an Angular application with Angular Universal and incorporating an SSL certificate?

Typically, when I want my angular applications to run locally over HTTPS, I install a certificate and make changes in the angular.json file like this: "serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { " ...

Premature conclusion of observable

I'm facing an issue with an element using the async pipe to subscribe to a Behavior Subject. showDiv$ = new BehaviorSubject<boolean>(false); showDivObv$ = this.showDiv$.asObservable().pipe( tap(() => console.log('here')), ...

What is the best way to retrieve or modify variable values in ReactJS similar to Angular?

Is it possible to achieve the following in ReactJS? How can I toggle a class on a specific element? This is the function I'm trying to implement: variable: any onclick() { this.variable = 'new value'; } <img src={ham} className=&quo ...

In order to access and showcase the current positions of each ngfor element, you need to obtain a reference to them

I am looking to retrieve references for each of the ngFor elements and display their latest Top and Left positions. Since these elements are draggable, their positions will be changing. While I can obtain a value for a single element, I am facing an issue ...

Transform Material UI Typography to css-in-js with styled-components

Can Material UI elements be converted to styled-components? <Container component="main" maxWidth="XS"> <Typography component="h1" variant="h5"> Sign in </Typography> I attempted this for typography but noticed that t ...

Issue with Node.js: Promise not completing execution

My current project involves retrieving data from multiple collections in MongoDB using Node.js and promises. Below is a snippet of the basic code I am using: await Promise.all( ["a", "b", "c"].map(async (collection) =& ...

Angular: When custom form components fail to respond to changes in value, it can feel as if the two-way data binding feature

Currently, I am working on developing my own custom form component that is facing a similar issue to the one discussed in this article I have forked the code mentioned in the article to demonstrate the issue ... https://stackblitz.com/edit/angular-8afwjx? ...

Is there a method to determine the total of values contained within an HTML table under designated headers? - IONIC

Details: My html table has 2 columns labeled as Debit and Credit, each with respective numbers listed below them. Goal: I am looking to calculate the sum of the numbers under both Debit and Credit. Please check out the about page in the repository for ...

Click on the button to insert a new row into the table

Recently I've begun learning Angular. In my project, there is a table and a button. When the button is clicked, a new row identical to the previous one should be added to the table. I have included a link to the StackBlitz demo below. Any guidance on ...

Encountering an issue during the registration of reducers with ActionReducerMap: "does not match the type 'ActionReducerMap<AppState, Action>'"

Here is a simplified version of my Angular 5 application. I have a reducer that needs to be registered in the root module. The problem arises in LINE A where I encounter the following error: ERROR in src/app/store/app.reducers.ts(7,14): error TS2322: Type ...

What is the process for attaching a method to an Angular component?

Utilizing a child component in the template: <slide-panel (swipeleft)="onSwipeLeft($event)" (swiperight)="onSwipeRight($event)" [activePane]="isLeftVisible ? 'left' : 'right'"> </slide-panel> In this case, I ...

Angular: issue with data binding between two components

I am facing an issue with data binding between two components. The first component sends the data as an object, while the second one iterates over it and displays the data in input fields (each value corresponds to an element). My goal is to update the val ...