Combine the values in the array with the input

I received some data from the back-end which is being written to a form, and it's in the form of an array of objects

Below is the code snippet:

 this.companyDetailsForm = new FormGroup({
        directors : new FormControl(response?.companyDirectors)
    });

Next, I iterate over the data in HTML using ngFor like so:

 <div *ngFor="let director of companyDetailsForm.controls['directors'].value; let i = index" class="form-group start-aligned" style="margin-left: 69px;margin-right: 69px">
                            <label>{{'Director' | localize}} {{i+1}}</label>
                            <input disabled type="text" class="form-control" pInputText formControlName="director.name" />
                        </div>

Here is how each director object looks like:

{ "id": 51, "name": "DIRECTOR, Test" }

If you need to add the 'name' field data to the input, here's how you can do it.

Answer №1

When dealing with response?.companyDirectors as an array type, it's important to note that directors is actually a FormArray, not a FormGroup.

directors : new FormArray(response?.companyDirectors)

Check out this article for more information on working with Angular Form Arrays.

Answer №2

As previously discussed in another response, when dealing with an array, using a FormArray is recommended. Personally, I prefer utilizing the FormBuilder, although it's not mandatory. In cases where data is retrieved asynchronously, you can employ setControl to incorporate director names. Here's a suggested approach:

companyDetailsForm!: FormGroup;

constructor(private fb: FormBuilder) {
  this.companyDetailsForm = this.fb.group({
    directors: this.fb.array([])
  });
}

Upon receiving the data, map the names from your array like so:

this.companyDetailsForm.setControl(
  'directors',
  this.fb.array(response && response.companyDirectors && response.companyDirectors.map(x => x.name))
);

Subsequently, in the template, iterate over the form array and utilize the index as the form control:

<div formArrayName="directors">
  <div *ngFor="let director of directorsArr; let i = index">
    <input [formControlName]="i">
  </div>
</div>

The directorsArr serves as a getter for your formarray:

get directorsArr() {
  return (this.companyDetailsForm.get('directors') as FormArray).controls;
}

DEMO available for further reference.

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

Difficulties with Grid Layout in React Material Design UI

I've been working on a project and I'm using the Material UI Grid Component to create a specific layout, but no matter what I do, I just can't seem to get it right. The layout I'm aiming for in my Dialog looks like this: In this layou ...

Converting SQL COUNT query to angularfire2: A guide on translating Firebase / angularfire2

In my firebase database, I have the following structure: "users" : { "USER1_ID" : { "email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="41343224337001393939396f222e2c">[email protected]</a>", ...

Experiencing difficulties with managing immutable state within ngrx framework

Hi there, I'm currently exploring ngrx and trying to implement immutable state management. However, I've run into some issues with getting it to work properly. Below is the reducer I am working with: https://stackblitz.com/edit/brewbrut?file=src ...

Can you explain the functionality of the DataTable drawCallback feature?

I'm currently facing an issue where CSS is not being applied to all cells in a DataTable based on their values when using drawCallback(). While the CSS gets applied to some cells, it's inconsistent. You can check out the JsFiddle of my problem he ...

Updating the NPM entry point without relying on an index.js file

After successfully publishing a private module to NPM, which contains shared code used by multiple services, I encountered an issue with the transpilation process. Since the code is written in ES6, it needs to be transpiled using Babel before being publish ...

Utilizing ng-model with invisible input field

UPDATED: Experimenting with a new approach: <input class="form-check-input deflog-check" type="checkbox" ngTrueValue = "1" ngFalseValue = "0" ng-value="chk_mail"> Now trying to retrieve the value in AngularJS like so: object2Edit.notification = N ...

Structure of a GraphQL project

What is the most effective way to organize a graphQL project on the server side? Here is my current project structure: src config models setup schema queries index userQuery resolvers index userRes ...

the undefined 'pipe' cannot be read

Trying to perform unit testing for an Angular component is a new experience for me. Currently, I am encountering a specific issue that I would like assistance with. The component in question contains the following select statement: this.store.select(getI ...

Unable to assign the selected attribute to a dynamically loaded Ion-select component in Ionic 2

I'm facing an issue with dynamically loading <ion-select> and setting default selection using the selected attribute. It doesn't seem to work as expected. Can anyone help me understand why? You can view the code on Plunker app/home.page.h ...

Create a new column in Material UI Grid by adding an empty div element instead of using padding

I'm currently getting acquainted with Material UI Grid and I am interested in adding an empty column (a blank space on the right of the first element) without utilizing padding. How can this be achieved? Here's a snippet of the code being discus ...

Having trouble with the `click()` function not working on a button while using Selenium in

Currently, I am running a selenium test on a remote server in headless mode using the chrome driver. However, when trying to click on a button with the following step, the button does not get clicked. Below is the test step attempting to click the element ...

React Router malfunctioning on production environment when integrated with an Express backend

My Single Page application is built using React for the frontend and Express for the backend. Within the application, there are two main components: and . The goal is to display the component when the "/"" URL is requested, and show the component for an ...

Triggering an event from a higher-level component to a lower-level component

Within the parent component named personDetails, there is a Submit button. This parent component contains multiple child components called person`. Each time I click on the Submit button, I need to trigger a method within the child component. Is it possib ...

What is the method for graphing data points that include two different y values?

I have been on the lookout for a solution to this question for quite some time now. While there are a few options that come close, I am yet to find the perfect answer. My goal is to create a line chart displaying water levels over time. I would like the d ...

Tips for receiving dual return values from an AJAX request

I am sending an array of table IDs to retrieve the table numbers associated with those IDs from the database. I need to add up all the default seats for each table ID and return the total. JAVASCRIPT : function showUser(str) { if ...

PHP encountering a bad escaped character while parsing JSON using JSON.parse

I'm encountering an issue with JSON parsing. In my PHP code, I have the following: json_encode(getTeams(),JSON_HEX_APOS); This returns a large amount of data. Sample data: To provide more clarity, let's assume I have this: my_encoded_data ...

Creating, editing, and deleting data in Ng2 smart table is a seamless process that can greatly enhance

While working on my Angular 2 project, I utilized [ng2 smart table]. My goal was to send an API request using the http.post() method. However, upon clicking the button to confirm the data, I encountered the following error in the console: ERROR TypeErro ...

When using EcmaScript imports with the 'node16' or 'nodenext' module resolution, it is important to include explicit file extensions in relative import paths. For example, did you intend to use './*.js'?

Within my package.json file, I have set "type": "module" and utilize SWC for compiling TypeScript code. For imports, I utilize import Example from './example'. In addition, I use the following script: "start": " ...

ngOptions compare by actual value

My webserver (node.js) serves a JSON file with a list of languages in the format: { "en" : "English", "fr" : "French" } and a separate JSON settings dictionary like this: { "currentLanguage" : "en" }. The select statement is as follows: <select ng-opti ...

Integrate the use of `Refresh Token` into an `Angular` application

In my current project, I am tackling the integration of Spring Security with OAuth2 and JWT: The author suggests that I can access resources using a token in the following manner: To access a resource, use the following command (assuming you have config ...