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

In the Node environment, why does null evaluate as less than 3 while also being greater than 3?

How come null is false when compared to 3 in node, and true when compared to 3? $ node > null > 3 false > null < 3 true ...

I'm currently working with ReactJS and attempting to retrieve JSON data from a REST API in JIRA, but I'm facing challenges in achieving this

I've been struggling for hours trying to understand why I am unable to access and transfer data in my array from the JSON data in JIRA using the REST API. Basically, I am attempting to retrieve the JSON data from the JIRA website via URL with Basic Au ...

Tips on adding TypeScript annotations to an already existing global function

I'm contemplating enhancing an existing project by incorporating TypeScript type annotations. Struggling to supply an external declaration file for a straightforward example: app.ts: /// <reference path="types.d.ts"/> function welcome (person ...

The difference between importing CSS in JavaScript and importing it directly in CSS lies in the way

Hello there, I am just starting out with web development and learning about Vue.js. In Vue 3, the recommended way to import CSS files from different packages is as follows: Method 1: Import directly in app.js //app.js import '../css/app.css'; i ...

Error encountered when extending Typography variant in TypeScript with Material UI v5: "No overload matches this call"

Currently, I am in the process of setting up a base for an application using Material UI v5 and TypeScript. My goal is to enhance the Material UI theme by adding some custom properties alongside the default ones already available. The configuration in my ...

When the input field is clicked, the file:/// URL is sent

Currently, my HTML page contains a form that includes an input field for URLs. Ideally, upon typing in the URL and clicking the button, I intend to be redirected to that website. However, the issue lies in the fact that instead of redirecting me to the p ...

The jquery function is functioning properly, but it only behaves as expected when clicked

Currently, I have implemented this JavaScript function: $(".plusmenus1").on('click', function() { $('.plusmenus1 i').toggleClass("fa-plus fa-minus"); $("#care_and_washing").toggleClass("collapsed_MB "); changeHeight(); }); ...

What is the best way to retrieve the value of a text box in VUEjs using its unique identifier?

In my form, there are a total of two text boxes with predefined values. However, I am looking for a way to retrieve the value of one specific textbox based on the entered ID number. For example, if I input "1," I expect to see the value of text box 1 only ...

Showing off HTML tags within react-json-tree

I have incorporated the following npm package into my project: https://www.npmjs.com/package/react-json-tree My goal is to showcase a json tree in react, but I am facing a challenge on how to include an HTML tag as a JSON value. Are there any alternative ...

The checkbox component is currently not displaying on the ngx-datatable

The following HTML code snippet demonstrates a sample layout. The operations are functioning correctly, however, the checkbox is not visible. <ngx-datatable style="width: 90%" class="material" [rows]="rows" ...

What are some ways to customize the appearance of gridlines in a PrimeNG p-table?

Currently, I am attempting to eliminate or modify the color of the gridlines on my p-table. I have gone through the code in the browser to locate the specific element responsible for these lines, but unfortunately, it has eluded me thus far. Even after t ...

React-Redux: Unable to access the 'closed' property as it is undefined

Encountered a problem when using dispatch() in React-Redux. Specifically, the action below: export const fetchMetrics = () => { dispatch(fetchMetricsBegin); APIService.get('/dashboard/info/') .then((response) => { ...

Building Unique Password Validation with Angular 5

I'm attempting to implement custom password validation for a password field. The password must be a minimum of 8 characters and satisfy at least two of the following criteria but not necessarily all four: Contains numbers Contains lowercase letters ...

Place information from an input field into a specific row within a table

Utilizing Angular 4, I am developing a frontend application for a specific project. The interface features a table with three rows that need to be filled with data from an external source. https://i.stack.imgur.com/Dg576.png Upon clicking the "aggiungi p ...

Despite using Vue and Vuex with Axios asynchronously, the getters are still returning an empty array

I am encountering an issue with getters that are returning the initial state (an empty array). In my component, I have a method called created that sets the axios call result into the state. created() {this.$store.dispatch("SET_STORIES");}, I am using m ...

Tips for customizing the border of an outlined TextField in MUI

Below is the current configuration of a TextField component: const styles = { resize: { fontSize: '50px', } } const textField = (props) => { const { classes } = props; return ( <TextField valu ...

Adding a JavaScript variable into a Django template tag

This particular situation has been presenting a challenge for me. So far, I have been using query parameters instead of a variable within the {% url %} tag. However, I can't help but wonder if there is a way to achieve this: I am interested in includ ...

Encountering a problem with TypeScript while employing Promise.allSettled

My current code snippet: const neuroResponses = await Promise.allSettled(neuroRequests); const ret = neuroResponses.filter(response => response?.value?.data?.result[0]?.generated_text?.length > 0).map(({ value }) => value.data.result[0]?.genera ...

What is the best way to send multiple variables to a url using jQuery ajax?

I am having trouble passing multiple values in the method below. Can someone help me with the correct syntax? I have attempted data: ('keyword='+$(this).val(),'id='10), as well as data: {'keyword='+$(this).val(),'id=&a ...

New feature in Safari extension: transferring window object from inject script to global page

Is it possible to transfer the window object from an injected script to a global.html page? I am attempting to pass the window object as part of an object to the global page. However, when I try to dispatch the message from the "load" listener function, i ...