Utilizing the patchValue function in Angular 2 Reactive forms to update elements within an FormControl Array

I am currently working with a reactive form in my project:

myForm = this.fb.group({
    ...
}

and I have been updating fields using buttons and functions like the following:

(click)="update('someKey', someValue)"

The update function is structured as shown below:

update(key, value) {
    if (key && value && this.myForm.contains(key)) {
        this.myForm.controls[key].patchValue(value)
    }
}

This approach has worked effectively so far, allowing me to use the same function for various form elements by passing their names as keys.

However, now there is an fb.array included in the form:

myForm = this.fb.group({
   ...
   items: this.fb.array([]),
}

With the structure as follows:

items: {"name":"", "description":"")

Now, I need to find a way to update the array values using a similar method. How can I modify

this.myForm.controls[key].patchValue(value)

To work with the fb.array? I believe I could pass the index of the array element I wish to access.

So it would be something like:

(click)="update(index, 'someKey', someValue)"


this.myForm.controls[items(index).controls[key].patchValue(value)

Or

this.myForm.get(`items${index}.${key}`).patchValue(value)

However, I have encountered issues with this implementation.

Answer №1

Just like clockwork, right after I posted the question, a solution popped up in a different forum (Shout out to andreysuperstar!)

this.myForm.get(`items.${index}.${key}`).patchValue(value)

I had overlooked including the dot between items and ${index}

Problem solved!

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

Guide for creating a function that accepts an array containing multiple arrays as input

I am working with a function called drawSnake and it is being invoked in the following manner: drawSnake( [ [0, 0], [0, 1], [0, 2], [0, 3], [0, 4], ] ); How should I format the input for this function? I have attempted using Array<Array<[numb ...

Updating form values using ngModel in Angular 6

After upgrading from Angular 5 to 6, I attempted to update my form: In Angular 5, I had: <select [ngModel]="toto" (ngModelChange)="onChange($event)" <option *ngFor="let toto of totos" [ngValue]="toto.id">{{toto.libelle}}</option ...

Is there an issue with the way I filled out this form?

I've successfully set up my form and everything is working smoothly. However, there's a problem when errors occur. The page refreshes and clears out any text that was entered before clicking the submit button, forcing users to re-enter all the in ...

What is the best way to add a repository in Nest.js using dependency injection?

I am encountering an issue while working with NestJS and TypeORM. I am trying to call the get user API, but I keep receiving the following error message: TypeError: this.userRepository.findByIsMember is not a function. It seems like this error is occurring ...

merge two structures to create a unified entity

I have been searching in vain, can you please advise me on how to combine these two simple forms into one? I want it to be like a box with a select option and a button. The challenge for me is merging the two different actions, ".asp", into one script fo ...

What is the most effective method for creating a personalized select in Angular?

I am currently working with the MEAN stack (Angular 6) and exploring different methods to build a custom and reusable <select> form control that utilizes an array of strings fetched from the backend server to generate all the <option> tags. For ...

Angular Injection Error: Received 1 argument instead of the expected 0

Although I have already looked for a solution to this problemhere, I am still struggling to resolve the error on my own. I recently started an Ionic project and followed this link to implement authentication using Angular. Everything seemed to be working ...

Tips for presenting a row that states "No data found" when the datasource is devoid in Angular using material2

Currently, I am utilizing angular/material2 to showcase a table. <mat-table class="table" #table [dataSource]="dataSource" matSort > <ng-container matColumnDef="{{col}}" *ngFor="let col of displayedColumns"> <mat-header-cel ...

Retrieving data from a different component in Angular 7

I need to separate the navbar and form-dialog components. I want to be able to access a value from form-dialog in the navbar. Here is my code for navbar.ts: import { Component, OnInit } from "@angular/core"; import { MenuItemModels } from "./models/MenuI ...

Unlocking the Secret: How to Bind a Global Touch Event Handler in Angular 4 to Prevent iOS Safari Page Drag

The issue at hand is that within my Angular 4 application, there is a D3.js chart that relies on user touch input for dragging a needle to a specific value. The drag functionality is triggered by 'touchstart', while the registration of the final ...

"Resulting in 'undefined' due to an asynchronous function call

Encountering an issue with async method implementation. In my authServices, there is a loginWithCredential function which is asynchronous: async loginWithCredential(username, password){ var data = {username: username, password: password}; api.pos ...

Troubleshooting Problem with Dependency Injection in Angular 2 Services

Within my application, there is a Module that consists of two components: ListComponent and DetailsComponent, as well as a service called MyModuleService. Whenever a user visits the ListComponent, I retrieve the list from the server and store it in the Li ...

Are SCSS style sheets being properly included in ng-packagr packaging?

I've been working on developing an Angular component library, packaging the modules for easy NPM installation. However, I took the old-school approach instead of using the CLI like Angular 6 recommends. Despite that, my components function properly wh ...

Sending a parameter between files in a React application: a step-by-step guide

I am currently working on a Pokedex website where I have Pokemon cards displaying data from a JSON file. When a user clicks on a card, a modal view appears with more detailed information about that specific card. I need help in ensuring that only the deta ...

The form embedded within the <tr> element seems to be malfunctioning

Hey there, I'm facing a little issue with my form that is nested inside a table content. It seems to not be working properly. Let me share the code snippet below: <table> <form name='editpo' method=POST action='js_buat_po.php? ...

Is there an issue with the newline character ` ` not functioning properly in TypeScript when used with the `<br/>` tag?

Having trouble with using New Line '\n' ' ' in Typescript Here is an example of my typescript code: this.custPartyAddress = estimation.partyName + ',' + '\n' + estimation.partyAddress + ',' + ...

Looking to display cities based on the country chosen in Angular?

Hi everyone! I need help with creating a cascade type dropdown for displaying cities based on the selected country. I have a list of about 3,000 cities, but I only want to show the cities from the chosen country. Here is the structure of the country: " ...

Bringing together a collection of objects connected by shared array elements

Given the types defined as: type A = { commonKey: { a: string }[] }; type B = { commonKey: { b: number }[] }; Is it possible to create the type below without explicitly specifying commonKey? type C = { commonKey: { a: string, b: number }[] } My initial a ...

How to bring in images from the assets folder using React and Typescript

I'm facing an issue where direct image importing is working, but when using object types, it's not functioning properly. Why could this be happening? I am currently working with "react": "^16.12.0" and "typescript": "~3.7.2" // ./src/assets/baby ...

A step-by-step guide on assigning values to an Angular Material Auto Complete component in Angular 7

Hey there! I'm currently using the Angular Material Auto complete component in my Angular 7 app and I'm trying to find a way to bind a value from an API response to it. Can someone help me out with a solution for this? HTML: <mat-form-field> ...