Tips for utilizing the patchValue method within a dynamic FormArray in Angular

When working with the first case (check out the DEMO link), patchValue() function can easily manipulate the select drop-down menu in a reactive FormGroup(), where only FormControl() is used. However, in the second case, I need to achieve the same functionality of updating the selected value directly when the user adds input. This time, I have to set the value using patchValue() inside FormArray(), which is currently not working as expected. How can I make it work within FormArray()?

FIRST CASE

app.component.ts

export class AppComponent {

      entityInfoForm: FormGroup;
    
      items = ['Mobile', 'Home', 'School'];
      
      constructor() {
        this.entityInfoForm = new FormGroup({
           name: new FormControl(""),
           control: new FormControl("")
        });
      }
    
      addCustom(v: string) {
        this.items.push(v);
        this.entityInfoForm.patchValue({control: this.items[this.items.length - 1]});
      }

      onSubmit() {
         console.log(this.entityInfoForm);
      }

   }

app.component.html

<form role="form" [formGroup]="entityInfoForm" (ngSubmit)="onSubmit()">

   <div class="form-group">
       <label for="usr">Name</label>
       <input type="text" class="form-control" id="name" formControlName="name">
   </div>
 
    <div class="form-group">
       <select formControlName="control">
         <option *ngFor="let item of items" [ngValue]="item">{{item}}</option>
       </select>
   </div>

   <button type="submit">Submit Form</button>

</form>

<input type="text" #custom>
<button (click)="addCustom(custom.value)">Add</button>

SECOND CASE Note: Here we use Dynamic FormArray, multiple options can be added in this case.

app.component.ts

export class AppComponent {

  entityInfoForm: FormGroup;

  items = ['Mobile', 'Home', 'School'];

  constructor() {
    this.entityInfoForm = new FormGroup({
       name: new FormControl(""),
       contact: new FormArray([
           new FormGroup({
                type: new FormControl(''),
                contact: new FormControl('')
           })
       ])
    });
  }

  addCustom(v: string) {
    this.items.push(v);
    this.entityInfoForm.patchValue({type: this.items[this.items.length - 1]});
  }

  onSubmit() {
     console.log(this.entityInfoForm);
  }
}

app.component.html

Name
       <div>
          <select class="form-control formControlName="type">
              <option *ngFor="let item of items" [ngValue]="item">{{item}}</option>
          </select>
       </div>
       
   </div>


</form>

<input type="text" #custom>
<button (click)="addCustom(custom.value)">Add</button>

Answer №1

If you need to update a value on a specific element, start by accessing that element within a formArray using the .get method. Then, insert the new value into the array.

this.entityInfoForm
  .get(['contact', 0])
  // .get('contact.0') // <-- alternative
  ?.patchValue({ type: this.items[this.items.length - 1] });

Try it out on Stackblitz

Answer №2

When updating a FormGroup with a complex object using patchValue, the values may not get applied to nested FormArrays.
To address this issue, I iterated through each item and added them individually to the FormArray.

In my particular situation:

this.form.patchValue(updatedFormObject);

The following code snippet did not update the array:

updatedFormObject.someImportantProperty

Instead, I utilized the following approach:

updatedFormObject.someImportantProperty?.forEach(item => {
  (this.form.get('someImportantProperty') as FormArray<FormGroup>).push(
    this.fb.group({
      property1: [item.property1, [Validators.pattern('...')]],
      property2: [item.property2, [Validators.pattern('....')]],
    },
    { validators: this.customValidator} ))
});

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

Top technique for verifying the presence of duplicates within an array of objects

How can I efficiently check for duplicates in typescript within a large array of objects and return true or false based on the results? let testArray: { id: number, name: string }[] = [ { "id": 0, "name": "name1" }, ...

The NGX-Graph nodes mysteriously change color to deep black when the third property is applied

My goal is to create a tree structure using ngx-graph and have each node linked to a pop-up using "@material-extended/mde". However, I encountered an issue when trying to define the pop-up content based on each individual node by using the property "data". ...

Tips for validating the loading variable during testing of the mockservice in angular5

In the process of creating a test case suite for my application, I am faced with the challenge of verifying and validating the loading variable in my component spec file. The scenario involves calling an API service from my component to retrieve data, show ...

Whenever I choose an ionic tab that has a changing URL, the tab does not appear as highlighted

My issue involves the ion tab setup in tabs.page.html. The user_id is set in the tabs.page.ts file within the same directory, ruling out any issues there. <ion-tabs> <ion-tab-bar slot="bottom"> ... <ion-tab-button tab=“profil ...

There seems to be an issue with the <mat-form-field> where normal input functions correctly, but encounters an error when trying to use mat

I've searched through other inquiries, but none have provided the solution I am looking for. <mat-form-field> <mat-select matInput placeholder="Favorite food"> <mat-option *ngFor="let food of foods" [value]="food.value"> ...

The ngmodel variable is not responding to dynamic changes

I'm currently working on dynamically changing a date and getting it to reflect in the view, but for some reason it's not showing up. When the date is hard-coded in an array like this, it works perfectly fine and shows up in the view. My date : Ar ...

Are you looking for straightforward dynamic directives that come with dynamic controllers and a scope?

Feeling like I have a simple problem to solve here. Working within the confines of a TypeScript + Angular application. Within a controller, I've got an array of similar directives that I want to utilize. These are essentially the panels strewn throug ...

An issue has arisen where Selenium Auth0 is unable to establish a connection with the server

I am using a protractor selenium test for an angular2 application that I execute with the command protractor conf.js --params.login.username=John --params.login.password=Doe. The purpose of the test is to attempt to log in to the backend and intentionally ...

Error: Angular 6 resolve consistently returns undefined

Seeking to implement my service for retrieving values from the database server and displaying them onscreen, I have set up a resolver for the service since the database can be slow at times. However, no matter what I try, the data received through this.ro ...

Encountering a 400 error when attempting to make a

After recently starting to use angular5, I encountered an error when attempting to insert a new row of data into a table. The error message was Failed to load resource: the server responded with a status of 400 (Bad Request) I've experimented with bo ...

How to bind values to @Directive's @Input properties using Angular Reactive Forms

While working on creating a Reactive Form using the FormBuilder from @angular/forms, I encountered an issue related to custom validating @Directives, @Inputs, and the FormBuilder. In this scenario, I have my own MatchValidator Directive. The question that ...

An error has occurred with mocha and ts-node unable to locate the local .d.ts file

This is the structure of my project: |_typetests | |_type.test.ts | | myproj.d.ts tsconfig.json Here is how my tsconfig.json file is configured: { "compilerOptions": { "module": "commonjs", "moduleResolution": "node", "lib": ...

An issue has occurred with error code TS2688: The type definition file for 'jquery' cannot be located. [Angular Application] --

I am currently working on developing an Angular web application with a specific theme that requires the inclusion of CSS and JS files. Majority of the JS files needed are jquery plugins, so I made sure to install them using the following commands: npm i j ...

Exploring the synergies between Angular 5 and atmosphere.js

I've been trying to incorporate atmosphere.js into my angular 5 project. So far, I've followed these steps: npm install --save @types/atmosphere.js npm install --save atmosphere.js In addition, I have set up a service as shown below: import { ...

UI5 Tooling generated an error stating that "sap is not defined" after a self-contained build

Having successfully developed an application using SAPUI5 1.108, I encountered a setback when attempting to deploy it to a system running SAPUI5 version 1.71. The older version lacks certain features, causing the application to fail. In order to address th ...

Exploring the most effective strategies for creating a brand-new type in TypeScript?

In the execution environment I'm working with, there are several global constants that represent different directions: TOP = 1 TOP_RIGHT = 2 RIGHT = 3 BOTTOM_RIGHT = 4 BOTTOM = 5 BOTTOM_LEFT = 6 LEFT = 7 TOP_LEFT = 8 These constants are not just ran ...

Angular2: using the #ngFor directive to assign a value to a component field

Here's a component I'm working with: @Component({ selector: "expenses-component", templateUrl: "expenses.html" }) export default class ExpensesComponent { private expenses: [] = [{name: "Foo", amount: 100}, {name ...

Is there a way to conduct testing on code within an Angular subscribe block without risking values being overwritten in the following subscribe blocks?

In my Angular application, I am using ngx-socket-io and have a component with several .subscribe blocks inside ngOnInit() that are triggered when data is received from the server. The issue arises when testing the component, as calling ngOnInit() in the t ...

Optimal strategies for managing subscriptions in Angular

I'm currently pondering about the concept of angular subscription and unsubscription. The amount of information available on this topic is overwhelming, making it hard for me to navigate through. When is the right time to unsubscribe from a subscript ...

What is the best way to convert Observable<Observable<{...}>[ ]> to Observable<{...}[ ]>?

I am currently working on merging two observable objects into a single observable to access data from both. These observables represent documents from separate collections in a NoSQL database, specifically a Cloud Firestore database. Both collections have ...