Angular: Issue with FormArrays not iterating properly

Apologies for the lengthy post, but I needed to provide a detailed explanation of the issue I am facing.

In my form, there is a control that contains an array of JSON data. I have created a reactive form based on this structure. Below are the JSON data and the TypeScript code:

JSON Data (retrieved from backend)

{
    "questionList": [
        {
            "questionCategory": {
                "questionCategoryName": "JAVA",
                "id": 40,
                "isActive": true,
                "timestamp": "2020-06-12 14:06:47.325"
            },
            // Other nested objects and arrays here
        },
        {
            // Second question object here
        }
    ],
    "empty": false
}

TS Code corresponding to this JSON data

// TypeScript code snippet here

Explaining the TS code: I have defined a form called updateQuestionForm which reflects the structure of the JSON data. Another form named optionForm is specifically for handling the options FormArray within updateQuestionForm. The onEdit() method is triggered by a button click event where JSON data is fetched from a Mat-Table.

The HTML Form

<form [formGroup]="updateQuestionForm" (submit)="onUpdateQuestionForm()">
  <!-- HTML form structure here -->
</form>

This represents the form structure related to the JSON data. While I am able to fetch and store values for most controls successfully, I am encountering issues with displaying the options control. Despite having 4 options in the JSON data, I face difficulties in rendering these options using ngFor inside formArrayName="options". This is resulting in no content being displayed after the h2 tag.

If anyone could guide me through this difficulty, it would be greatly appreciated. For reference, I was following this link regarding looping through formArrayName.

https://i.sstatic.net/DES2k.png

Answer №1

If you’re looking to streamline your code for updating question data, using just one form instead of two can simplify things significantly.

After tweaking your code, I found a simpler solution that works perfectly for me. Feel free to take a look at the updated version here.

What changes did I make?

1) First off, I reorganized the form structure in the ngOnInit() function based on the examples you provided.

2) I created an updateQuestionData() function where I update the form with JSON data. I broke down the options into individual form groups within the function.

Feel free to test out modifying the values on the form to see how the updateQuestionForm function dynamically updates the data.

I believe this revised approach will simplify your process and optimize your code overall.

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

React Router V6 - page is not found in browsing history

Currently, I am encountering an issue with react router v6. While on the detail page, if I press the arrow in Chrome to go back to the previous page, it takes me to the page before the previous one. I checked the history by long pressing on the back arrow, ...

Having trouble with protractor's sendKeys function when trying to interact with md-contact-chips

Does anyone know how to set a value using sendKeys in Protractor for md-contact-chips? I attempted to use element(by.model('skills')).sendKeys('Java'); but it doesn't seem to be working. Any suggestions on how to approach this in ...

Fetching data before the Angular app is fully loaded

I need a solution to initiate a service when my app loads. If the service fails, I want to display an error message instead of continuing to load the app. I have read about using APP_INITIALIZER, but it doesn't seem to fit my requirements. In my Angu ...

Experiencing difficulties loading Expo Vector Icons in Nextjs

I've spent countless hours trying various methods to accomplish this task, but unfortunately, I have had no luck so far. My goal is to utilize the Solito Nativebase Universal Typescript repository for this purpose: https://github.com/GeekyAnts/nativ ...

Enhance your PrimeNG p-calendar by customizing the background-color of the dates

Hello, I am currently attempting to customize the appearance of the p-calendar, but I am struggling with changing the color of the displayed dates. Can anyone provide assistance? Thank you in advance. Below is my template: <div class="p-field p-co ...

Angular 6 Material now allows for the selection of a mat-tab-link by displaying an underlining bar

My website features a mat-tab-nav-bar navigation bar, but I'm facing an issue with the mat-tab-link blue underlining bar. It doesn't move to highlight the active button, instead, it stays on the first button. However, the buttons do change into t ...

The drop-down menu selection is non-functional on mobile and iPad devices when using Bootstrap

<div class="panel panel-default"> <select> <option value="B3">B3</option> <option value="B4">B4</option> <option value="B5">B5</option> & ...

Enhancing JavaScript functions with type definitions

I have successfully implemented this TypeScript code: import ytdl from 'react-native-ytdl'; type DirectLink = { url: string; headers: any[]; }; type VideoFormat = { itag: number; url: string; width: number; height: number; }; type ...

converting JSON data to XML format using Java

I am facing an issue while trying to convert a json file into xml format. Here is the code snippet I am using: String strinput= query; ArrayList<String> urls = new ArrayList<>(); String keyofaccount = "mykey"; String bingApiUrlp ...

What is the syntax for populating an attribute on the same line as v-for in Vue.js?

I am currently working on a simple loop utilizing Vue to iterate over an array of objects and populate table rows. <tr v-for="user in users"> <td>{user.name}</td> <td>{user.id}</td> </tr> However, I also need to as ...

Regularly updating a book's interactive pages with turn.js technology

I experimented with generating dynamic content in turn.js using the sample provided here. This is an excerpt of the code I have written: <body> <div id="paper"> </div> </body> <script type="text/javascript"> $(win ...

Utilizing the Bing Translation API to translate an entire webpage

I am currently attempting to use the Bing API to translate an entire webpage instead of using the Bing widget. This is because I want to create a custom design for the translation panel, However, I have been unable to find any resources on how to do this ...

Unable to transform dynamically loaded text area into CKEditor

Executing the get_content function upon a link click. function get_content(n) { var hr=new XMLHttpRequest(); var url="./updatecontent.php"; var vars="id="+n; hr.open("POST",url,true); hr.setRequestHeader("Content-type","application/x-w ...

Enhancing the appearance of div content in Angular by utilizing local template variables and material elements

Within this particular implementation, I have utilized an md-sidenav component with a local template variable #sidenavsearchArea. <md-sidenav #sidenavSearchArea align="" mode="push" opened="false"> sidenav content here.. </md-siden ...

The reason behind a loop being caused by an IF statement

Here is a snippet of code that I'm trying to understand: ReactDOM.render(<Change />, document.getElementById('app')); function Change() { const [i, setI] = React.useState(0); let rnd = 9; if (i !== rnd) { setTime ...

What is the process for sending a post request in the inline editor of Dialogflow?

Currently, I am utilizing the blaze tier, so there should be no billing concerns. I have also added "request" : "*" in my package.json dependencies. Check out my code index.js below: ` 'use strict'; var global_request = require('requ ...

The Express.js main router is functioning properly, however, the other routers connected to it are experiencing

I'm encountering an issue with my routers. The main route /weather is working fine, but other routes connected to it are not functioning properly. app.js const express = require('express'); const weatherRoute = require('./back/routes/w ...

Sharing a variable between an Angular component and a service

I am attempting to pass a variable from a method to a service. from calibration-detail.component.ts private heroID: number; getTheHeroID() { this.heroService.getHero(this.hero.id).subscribe(data =>(this.heroID = data.id)); } to step.service.ts I ...

Guide to utilizing exact matching functionality in ExpressJs router

In my ExpressJs application, I have defined two routes like so: router.get("/task/", Controller.retrieveAll); router.get("/task/seed/", Controller.seed); When I make a request to /task/seed/, the Controller.retrieveAll function is call ...

Encountered CSRF validation error while working with a Python Django backend in conjunction with React frontend using Axios for making POST requests

I recently completed a tutorial at and now I'm attempting to add a POST functionality to it. Despite obtaining the csrf from cookies and including it in the "csrfmiddlewaretoken" variable alongside a test message in json format for the axios function ...