What could be causing the FormArray value to not update when I make changes to an input field?

My Angular reactive form includes several FormControl elements and one FormArray element.

competitionForm!: FormGroup;    
    
this.competitionForm = new FormGroup({
  name: new FormControl(this.competition.name, []),
  about: new FormControl(this.competition.about, []),
  rules: new FormControl(this.competition.rules, []),
  competitorNames: new FormArray([]),
});

The FormArray competitorNames contains an array of FormControl elements with string values. I have connected the competitionForm to a form in my HTML template using a custom input component (app-input). This component takes a FormControl as input: [control].

<form [formGroup]="competitionForm">    
    <div formArrayName="competitorNames">
        <ng-container *ngFor="let competitor of refCompetitorNames.controls">
          <app-input
            [control]="$any(competitor)"
            [placeholder]="'name'"
            [type]="'text'"
          ></app-input>
        </ng-container>
      </div>
</form>
get refCompetitorNames() {
  return this.competitionForm.get('competitorNames') as FormArray;
}

When I retrieve the form data using

this.competitionForm.value.competitorNames
, it always returns the same data regardless of entering new values in the input element. However, the input elements display the values correctly, indicating that the template form is bound to competitionForm.

This method works fine for FormControl elements but faces issues with FormArray elements. Below is an example of how I pass control for a single FormControl, where updated data is obtained as expected.

The key difference lies in how I pass the control.

<form [formGroup]="competitionForm">    
    <app-input
        [control]="$any(competitionForm.controls).name"
        [placeholder]="'name'"
        [type]="'text'"
      ></app-input>
</form>

Edit: Issue Resolved

I have identified the problem and found a solution by accessing form data differently. Using

this.refCompetitorNames.at(i).value
now retrieves the correct data. However, I am still unsure why
this.competitionForm.value.competitorNames
does not reflect updated data (specifically with FormArray).

Answer №1

After some investigation, I was able to pinpoint the source of the issue. The solution lies in accessing form data using a different method. By utilizing

this.refCompetitorNames.at(i).value
, I am now able to retrieve the accurate information.

It is still unclear to me why

this.competitionForm.value.competitorNames
does not reflect the updated data (specifically when dealing with 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

What could be the reason for TypeScript being unable to recognize my function?

In my code, I have a Listener set up within an onInit method: google.maps.event.addListener(this.map, 'click', function(event) { console.log(event.latLng); var lt = event.latLng.lat; var ln = event.latLng.lng; co ...

Encountering an AbstractControl error during the build of my Angular project

I'm encountering an error while building my code. ERROR in src\app\components\search.component.html(105,62): : Property 'controls' does not exist on type 'AbstractControl'. Error occurred at line 105, character 62: ...

Tips for effectively implementing ng-bootstrap in Angular 18

After upgrading my angular app to the latest version, Angular 18, I encountered an issue where there is no compatible version of ng-bootstrap available for Angular 18. While trying to resolve dependencies, I came across the following errors: npm error Fou ...

Steps for incorporating moment.js into an Angular 2 project

Having trouble importing moment.js into my angular2 application despite following various guides and solutions provided. Even though the package is present in my IDE (Visual Studio) and the moment.d.ts file is easily found, I keep encountering errors when ...

Excluding Layout from Display on Certain Pages in a Next.js 13 App Router

I am currently working on a personal project that involves using the Next.js 13 app router, and I have encountered a dilemma. Within my project, there is a header component injected into the layout.tsx file located in the root directory. However, I also ha ...

What are the most effective techniques for utilizing promise.all in your codebase?

When trying to consolidate responses from two API calls in the code below, I'm facing an issue where Promise.all is not being invoked. Any suggestions on what might be implemented incorrectly and the best practice to achieve this using Promise.all? T ...

Exploring the capabilities of Vitest by testing a RESTful API in SvelteKit

I am looking to create unit tests for a REST API built with SvelteKit, but most of the available resources focus on testing svelte components. Additionally, I prefer to avoid using Playwright as I do not require browser testing and want to steer clear of d ...

What could be the reason for my Angular 2 app initializing twice?

Can someone help me figure out why my app is running the AppComponent code twice? I have a total of 5 files: main.ts: import { bootstrap } from '@angular/platform-browser-dynamic'; import { enableProdMode } from '@angular/core'; impor ...

Get rid of the Modal simply by clicking on the X mark

Objective: The modal should only be closed by clicking the X mark and not by clicking outside of it. Challenge: I am unsure how to resolve this issue when using the syntax code [config]="{backdrop: 'static'}" Additional Information: I am new ...

Automatically pass on parameters from a universal function

If I have an object with functions that return numbers: const obj = { foo() { return 1; } bar() { return 2; } baz(num: number) { return num; } } The expected output of typeof obj would be: { foo: () => number; bar: () => number; baz ...

Having trouble executing a method from a template in Angular 5?

Angular has a useful capability that almost every developer has utilized at some point: calling methods from templates. I've personally been using this feature for months without any issues. However, recently I encountered a problem. I have a menu co ...

What is the best way to apply filtering to my data source with checkboxes in Angular Material?

Struggling to apply datatable filtering by simply checking checkboxes. Single checkbox works fine, but handling multiple selections becomes a challenge. The lack of clarity in the Angular Material documentation on effective filtering with numerous element ...

Evaluating Angular2 components that have indirect dependencies

Starting with Angular2, I make sure to test each component I create from scratch. When it comes to writing tests for components, I must initialize TestBed to ensure that the component under scrutiny has all its necessary dependencies resolved. Currently, ...

Using [(ngModel)] on a field within an object that is nested inside another object

I am facing a challenge as I attempt something that may or may not be feasible. Within an Angular form, I have an object structured like this: export class NewUserRegisterModelDTO{ userData:UserDetailModelDTO; roles:RoleModelDTO[]; ownerData:O ...

Using :global() and custom data attributes to apply styles to dynamically added classes

Currently, I am working on creating a typing game that is reminiscent of monkeytype.com. In this game, every letter is linked to classes that change dynamically from an empty string to either 'correct' or 'incorrect', depending on wheth ...

Are you looking to create a dynamic quiz platform with Angular?

Within my program, there are two choices available: one is to host the quiz and the other is to join the quiz. Upon hosting a quiz, a random code will be created and must be shared so that participants can join the quiz. Which Angular concept should be u ...

What could be the reason for the 'tsc' command not functioning in the Git Bash terminal but working perfectly in the command prompt?

I recently installed TypeScript globally on my machine, but I am facing an issue while trying to use it in the git bash terminal. Whenever I run tsc -v, I encounter the following error: C:\Users\itupe\AppData\Roaming\npm/node: l ...

Error: The page you are trying to access does not have a valid default export. The provided type is not acceptable

Hello, I am a newcomer to the world of react and NextJS. Currently, I am working on a small project using NextJS 13 where I am attempting to display products stored in a JSON file (which will later be moved to a database). The application runs correctly, ...

Dealing with CORS challenges in Angular 2 when trying to fulfill a promise

While attempting a service call in Angular, I encountered an error message: XMLHttpRequest cannot load http://geo.groupkt.com/ip/172.217.3.14/json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http:/ ...

The upcoming development does not involve creating an entire HTML webpage using on-demand static site generation (SS

I’m encountering a problem when utilizing getStaticPaths and getStaticProps to create an on-demand SSG for a sharing page. My setup involves Next v12.1.0 and React 17.0.2. After building a specific /[id] page, I can retrieve the data but the HTML output ...