A guide on assigning a value to an array within a formgroup

if (Object.prototype.hasOwnProperty.call(data, 'checklists')) {
      if (Array.isArray(data.checklists)) {
        data.checklists.map((dt: any) => {
          dt.tasks.forEach((task: any) => {
            const dataArray = new FormGroup({});
            dataArray.addControl('failed', new FormControl(true, Validators.required));
            dataArray.addControl('remarks', new FormControl('', Validators.required));
            dataArray.addControl('task', new FormControl(task));
            formArray.push(dataArray);
          });
        });

        data.checklists.map((dt: any) => {
          assetArray.push(dt.asset);
        });
      }
    }
    const formField = {
      remarks: new FormControl(''),
      tasks: formArray,
      room: this.creds.credentials['room'],
      asset: assetArray
    };
    return this.fb.group(formField);

Trying to figure out how to correctly set the value using addControl with new FormControl in order to create a form for both creating and editing data.

I attempted to modify it like this:

            dataArray.addControl('failed', new FormControl(task['failed], Validators.required));
            dataArray.addControl('remarks', new FormControl(task['remark'], Validators.required));
            dataArray.addControl('task', new FormControl(task['task']));

However, the data doesn't display in the form. It does show up correctly when checked in the console. https://i.sstatic.net/oQp3L.png

Answer №1

Have you tried utilizing the patchValue method to set a value?

Here is an example I have provided:

const group = new FormGroup({
  control1 : new FormControl(),
  control2 : new FormControl(),
  control3 : new FormControl()
});

const array = new FormArray([this.group]);

If you need to assign a value to a FormGroup, make sure to set the value for each FormControl in the group using patchValue()

this.group.patchValue({control1:'your value here'})
this.array = new FormArray(this.group)

You may find the following links helpful:

https://angular.io/guide/reactive-forms

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

I need assistance with this ajax/javascript/php

I am currently working on creating a dynamic chained list. The idea is to have the user make selections from the first four dropdown lists, and based on their choices, a fifth dropdown list should appear. However, I am facing some issues with my code as th ...

API requests in React Native can be conveniently handled using a proxy

Is it possible to utilize a proxy for API calls in React Native? I have attempted setting the property "Proxy": "https://someapi.com" in package.json, but it seems to be ineffective. Can a proxy be used effectively in React Native? ...

Gif stubbornly refusing to fade out even after the .fadeOut command is called

Having trouble making a gif fade out after the page loads? Here's my attempt so far: I want the overlay, which includes a white background and the gif, to gradually become transparent once the rest of the page is fully loaded. Take a look at the fol ...

Able to retrieve individual elements from an array, but not able to loop through them

I am facing an issue with my code where I have two arrays - one containing URLs and the other external data. These two arrays are perfectly aligned, but when I try to access them in a loop using AJAX requests, only the first element of the URL array prints ...

Restrict OrbitControls to a specific region of the page that is separate from the rendering area

As an experienced COBOL programmer delving into the world of Javascript and Three.js for a personal project, I've been grappling with a particular question for the past couple of days. Despite scouring StackOverflow for answers related to OrbitControl ...

Bring in the content to Notepad utilizing jQuery

How can I export data to Notepad? I have fields for Name, Age, and WorkingStatus that are input as text and textarea. Is there a demo or code available to help me insert this data into Notepad? ...

What is the best way to connect my 'Projects' folder to app.js within a React application?

import "bootstrap/dist/css/bootstrap.min.css"; import Navbar from './components/Navbar'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; import Home from './components/Home'; import Project ...

An array containing numerous "case" triggers

var message = "hello [[xxx]] bye [[ZZZ]]" var result, re = /\[\[(.*?)\]\]/g; while ((result = re.exec(message)) != null) { switch (result[1].toLowerCase()) { case "xxx": console.log("found xxx"); br ...

Fade effect not working with Bootstrap Modal

I am encountering an issue with the Twitter Bootstrap modal while trying to display post details on WordPress. The problem is that when the modal opens, the entire screen turns grey and nothing in the modal is clickable. I can only exit this mode by pressi ...

Manipulating Arrays in order to delete an index

I have been working on a function to manipulate arrays... var myArray = [2, 1, 1, 1, 1]; and I want to transform it into this [3, 1, 1, 1] The function I created accepts 3 parameters ArrayToProcess - the array that will be processed indexTarget - ...

Error encountered in Next.js: The function 'useLayoutEffect' was not successfully imported from 'react' (imported as 'React')

I've been in the process of migrating an application from CSR (using webpack only) to SSR, and I'm utilizing Next.js for this transition. Following the migration guide provided by Next.js for switching from vite (specifically focusing on parts r ...

Utilize Observables to track changes in Ionic 2 form input elements

Is there a way to create an Observable from an Ionic 2 form element without directly accessing the DOM? While the Observable.fromEvent function is useful for events, I have the form element reference from the FormBuilder service, not the actual element it ...

How can I detect Mongoose events through syntax?

Is there a way to detect the open event in Mongoose based on their documentation located here? According to the documentation, once connected, the open event is fired on the Connection instance. If you're using mongoose.connect, the Connection is m ...

I'm encountering some issues with routing within Node.js and Express framework

I have developed a single page application (SPA) using React framework. Currently, I am working on creating an API with Express in Node.js for my app. Below is the code snippet of my server: const express = require('express'); const app = expr ...

Tips for disabling the download prompt in Chrome with the help of Protractor

Customize Chrome options for better performance: 'chromeOptions': { args: [ 'disable-extensions', 'safebrowsing-disable-extension-blacklist', 'safebrowsing-disable-download-protection', ...

The use of the "declare" keyword is prohibited within the `script setup` section of Vue

I need to integrate the function getCookie into my Vue file. This function is already defined in the HTML file where the Vue file will be injected. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" ...

Listening for keypress events on a div element using React

I'm currently struggling with implementing a keypress listener on a component. My goal is to have my listener activated whenever the "ESC" key is pressed, but I can't seem to figure it out. The function component I am working with is quite stra ...

Angular2 ngFor: Mistakes in my code?

I'm struggling to resolve the "Cannot find a differ supporting object '[object Object]' of type 'object'" error, which appears to be quite common in Angular2. I'm hoping someone might have encountered a similar issue. Suppose ...

Enhancing the style of child elements in jQuery using CSS

My goal is to create a popup that appears upon mouse hover using jQuery and CSS. The code functions properly, but I'm encountering difficulty adding CSS to the child elements within the popup window. Below is the jQuery code: $(document).ready(fun ...

Dynamically load highcharts with a dynamic configuration setting

I am currently utilizing highcharts and dynamically loading them using ng-repeat. <div ng-repeat="(key,value) in chartCheckboxes track by $index"> <div class="card" id="{{key}}"> <div class="card-body" id="{{key}}"> ...