Connect values with formBuilder in Angular

I have an array of objects structured like this

const premises = [
  {
    question: '1',
    value: '1'
  },
  {
    question: '2',
    value: '2'
  },
  {
    question: '3',
    value: '3'
  }
];

I am looking to generate form controls dynamically based on the data, similar to this

this.formBuilder.group({
  1: [{ value: 1 }, [Validators.min(0), Validators.max(100), Validators.required]],
  2: [{ value: 2 }, [Validators.min(0), Validators.max(100), Validators.required]],
  3: [{ value: 3 }, [Validators.min(0), Validators.max(100), Validators.required]]
});

This is just a simplified example, there could be more values in the premises array.

I attempted something along these lines


this.formBuilder.group({
  premises.forEach((x) => {
    x.question: [{ value: x.value }, [Validators.min(0), Validators.max(100), Validators.required]]
  });
});

However, I haven't been successful in creating dynamic controls and values.

Answer №1

The ForEach loop does not allow you to return anything, resulting in undefined as the default output. Therefore, using forEach will be ineffective. Instead, consider utilizing Array.reduce to generate a dynamic formControl object similar to the example below:

Give this a try:

let group = premises.reduce((acc, x) => {
   acc[x.question] = this.fb.control({ value: x.value, disabled: false }, [
    Validators.min(0),
    Validators.max(100),
    Validators.required,
  ]);
  return acc;
}, {});

this.formBuilder.group({
  ...group,
});

Alternatively,

Utilize a for loop to create a dynamic object:

let fGroup = {};
for (let i = 0; i < premises.length; i++) {
  fGroup[premises[i].question] = this.fb.control(
    { value: premises[i].value, disabled: false },
    [Validators.min(0), Validators.max(100), Validators.required]
  );
}

 this.formBuilder.group({
  ...fGroup,
});

Answer №2

To tackle this issue effectively, I recommend setting up a form array. Since "Premises" is an array, utilizing a FormArray along with handy functions like push can greatly benefit the organization of such data.

const premises = [
      { question: '1', value: '1' },
      { question: '2', value: '2' },
      { question: '3', value: '3' }
    ];

this.formBuilder.group({
  premises: this.formBuilder.array(
    this.premises.map(premise => 
      this.formBuilder.group({ 
        value: [premise.value, [Validators.min(0), Validators.max(100), Validators.required]]
    })
 )
)

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

Angular 5 does not allow function calls within decorators

I encountered an issue while building a Progressive Web App (PWA) from my Angular application. When running ng build --prod, I received the following error: ERROR in app\app.module.ts(108,64): Error during template compile of 'AppModule' Fu ...

Encountering errors when subscribing to a BehaviorSubject in Angular 8

I am currently working on a Single Page Application using Angular 8 where I am trying to pass data from a component to a service. In the service, I am subscribing to it using rxjs BehaviorSubject. However, when I compile the code using Angular CLI, I encou ...

What's the reason Ionic is not refreshing my list after I remove items using the search bar?

I've been working on creating a search bar for my list using Ionic 4. I followed this tutorial: The search function is functioning correctly, but I noticed that when I delete letters from the search bar and clear the entire line, the list does not up ...

The sticky navbar fails to stay in place when the content becomes too lengthy

This is my current state of code (minified, for explanation only) index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-w ...

Unable to expand the dropdown button collection due to the btn-group being open

Having trouble with the .open not working in Bootstrap 4.3 after adding the btn-group class to open the dropdown... I am looking for a way to load the dropdown without using JavaScript from Bootstrap. This is the directive I am trying to use: @Host ...

Listening for value changes on a reactive form seems to be a challenge for me

While attempting to listen for value changes on a reactive form, I ran into the following error: This expression is not callable. Type 'Observable<string | null>' has no call signatures. searchWord = this.fb.group({ word: ['' ...

The module 'json-stringify-safe' could not be located

Encountering an issue while executing the command - ionic serve The code was functioning properly on a different system but seems to be causing trouble for me at the moment. https://i.sstatic.net/X1JG0.png ...

What is the solution for the warning "Solid's reactivity is broken when destructuring component props"?

Just starting out with SolidJS and encountering an issue with my UI setup import { render } from "solid-js/web"; import { createSignal, Show } from "solid-js"; import { createStore } from 'solid-js/store'; function Form() { ...

The Tauri JS API dialog and notification components are failing to function, resulting in a null return value

Currently, I am getting acquainted with the tauri framework by working on a small desktop application. While testing various tauri JS API modules, most of them have been functioning as expected except for the dialog and notification modules. Whenever I tes ...

The edited input is not being shown on the console when using the PUT method

I retrieved the data for the input fields (title and body) from this specific source (https://jsonplaceholder.typicode.com/posts). My goal now is to modify the text in either the title or body, so that when I use console.log(), it will show the updated tit ...

Differences between Typescript React.ReactElement and JSX.Element

Simple Inquiry: I'm curious about the contrast between React.ReactElement and JSX.Element. Can you clarify if they are interchangeable, and advise on when to opt for one over the other? ...

Restrict the scope of 'unknown' to an object containing only a string-field without resorting to 'any'

Currently, I am working on validating the data that is being received by my application. To illustrate, consider the following scenario: function extractField(data: unknown): string { if (typeof data !== 'object') { throw new Error(& ...

Error in Visual Studio: ASP.NET Core application integrated with Angular is unable to run the API

I recently went through a tutorial on creating an ASP.NET Core app with Angular in Visual Studio, Although I successfully got the Angular project running, I encountered an issue where the API component did not run. Despite trying to access the API endpoin ...

What is the best way to disconnect an ngFor loop from its original context and reconnect it to a wrapping component's context when utilized as projected content?

In my project, I've developed a custom wrapping component that accepts <div *ngFor='let item of items> as part of its projected content. My goal is to replace the immediate bindings within the projected content with those defined in the wr ...

Could you confirm if this is a TypeScript function?

Recently, while delving into the vue-next source code, I stumbled upon a particular line that left me puzzled. Due to my limited experience with TypeScript, I found myself struggling to grasp its purpose. Could someone clarify if this snippet constitutes ...

Object.assign versus the assignment operator (i.e. =) when working with React components

Just a quick question: I've come across some answers like this one discussing the variances between Object.assign and the assignment operator (i.e. =) and grasp all the points made such as object copying versus address assignment. I'm trying to ...

Using Vue.js, learn how to target a specific clicked component and update its state accordingly

One of the challenges I'm facing is with a dropdown component that is used multiple times on a single page. Each dropdown contains various options, allowing users to select more than one option at a time. The issue arises when the page refreshes afte ...

What is the proper way to implement 'page-break-before or after' in a PrimeNG table?

Whenever I include the following code snippet in my primeNG table: <tr> <td> <div></div> <div style="page-break-before:always; background-color: blue"></div> </td> </tr> I added back ...

Using 'cy.get' to locate elements in Cypress tutorial

Is there a way to search for one element, and if it's not found, search for another element? cy.get(@firstElement).or(@secondElement).click() Can I use a function similar to || in conditions for this scenario? ...

Encountering multiple error messages from Protractor @types

Lately, I've been using the Angular2 Webpack Starter created by AngularClass and I've started encountering some perplexing errors with Protractor. When trying to build, these errors pop up: Module 'webdriver' has no exported member &ap ...