Displaying elements within a collection of forms

I am currently working on displaying users' names and a list of their courses in an Angular project. Each user has a different number of courses, so I am experimenting with using Angular Form Array to achieve this functionality.

Below is a snippet from my TypeScript file:

this.form = this.fb.group({
  name: [''],
  courses: this.fb.array([
    this.fb.group({          
      name: [''],     
    })
  ]),
});

get courses() {
  return this.form.controls["courses"] as FormArray;
}

and in my HTML file:

<form [formGroup]="form" (ngSubmit)="onSubmit()">
   <div class="mb-3">
     <label>Name</label>
     <input type="text" formControlName="name"/>                    
   </div>
   <div class="mb-3">
     <label>Courses</label>                    
     <div formArrayName="courses">
       <div *ngFor="let course of courses.controls; let i = index">
         <div [formGroupName]="i">
            <input type="text" formControlName="name"/>
         </div>                                                                                                       
       </div>
     </div>
   </div>      
</form>

I am facing an issue where a user with two courses is only displaying one of them. Can anyone help me troubleshoot this problem?

Happy new year! :)

Answer №1

It is important to ensure that every instance of a course requires a corresponding FormGroup instance in the array of courses.

for (let course of this.data.courses) {
  let courseFormGroup = this.newCourseFromGroup();
  courseFormGroup.patchValue(course);

  this.courses.push(courseFormGroup);
}

To prevent redundant code when creating a Course FormGroup, I recommend creating a function like the one below:

newCourseFromGroup() {
  return this.fb.group({
    name: [''],
  });
}

There is a concern that the current code will add an extra FormGroup instance to the courses FormArray. To address this, initialize the courses FormArray with a default FormGroup only if the data is not present, as shown below:

this.form = this.fb.group({
  name: [''],
  courses: this.fb.array([]),
});

if (this.data) {
  for (let course of this.data.courses) {
    let courseFormGroup = this.newCourseFromGroup();
    courseFormGroup.patchValue(course);

    this.courses.push(courseFormGroup);
  }
} else {
  this.addCourse();
}

Check out the Demo on StackBlitz

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

How to identify generic return type in TypeScript

My goal is to develop a core dialog class that can automatically resolve dialog types and return values based on the input provided. I have made progress in implementing this functionality, but I am facing challenges with handling the return values. Each ...

A guide on transferring received data from dataService within the parent component to the child component in Angular2

Within the context of my application, there exists a parent component named app-parent and a child component called app-child. In app-parent, I retrieve data from a DataService. @Component({ selector: 'app-parent', providers: [DataService] ...

What could be causing the sorting function to malfunction on certain columns?

My table's column sorting feature works well with first name and last name, but it seems to have issues with dl and dl score columns. I need assistance in fixing this problem. To access the code, click here: https://stackblitz.com/edit/angular-ivy-87 ...

Instructions for retrieving the chosen option from a dropdown list within a formarray

<ng-container formArrayName="actors"> <ng-container *ngFor="let actor of actors['controls']; let i = index"> <ng-container> <div [formGroupName]="i"> <div class= ...

Webpack is having trouble identifying Node's process module

It has been more than ten years since I last worked with JavaScript, but recently I had an idea for an app that would be best implemented as a NodeJS app. As I delved into the modern JS ecosystem, like many others, I found myself thoroughly confused, haha. ...

Angular's conditional statement for handling three different cases

Can someone explain how to create a switch case or if statement in Angular that accommodates 3 different options? if Boards.status==1 then "Approved" if Boards.status==2 then "Pending" if Boards.status==3 then "Rejected" I attempted this approach, but ...

Utilizing TypeScript to invoke a method via an index signature

Here is a snippet of my code, where I am attempting to call a method using an indexed signature. It functions properly when the function name is manually added, but how can I call it using object notation for dynamic calls? createFormControl(formControls: ...

Each time I use console.log to display a user's radio button choice, the output is consistently lagging by one step

It seems that I am experiencing an issue where the console.log output for a user's radio button selection is always one step behind. This occurs even though I have initially set the default radio button selection to "all". For example, when a user cli ...

Modifying PDF files using Angular 4

Encountering a CORS problem in node v8.9.4. Error message - Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200& ...

React: Switching PopUp causes the entire component to be re-rendered

Currently, I am in the process of familiarizing myself with React, so I appreciate your patience. I am developing a component using MaterialUI which consists of a grid and a PopOver. A basic mockup of this component is as follows: export const Overview ...

Connecting the SignalR client to various servers

I am currently incorporating SignalR version 2.x into my ASP.Net MVC application, which is also using the same version of SignalR in my Angular client app. The ASP.Net MVC application is hosted at http://localhost:42080, while the Angular app is hosted at ...

Node's TypeScript parser loses the order of same name-tags when converting XML to JSON

I've experimented with xml2js and fast-xml-parser and received similar results from both (in different formats, but that's not the focus here) This specific example is from fast-xml-parser Here's the XML data: <test version="1" ...

What are the best ways to enhance change detection efficiency in Angular?

One issue I am facing involves two components and a service. It appears that when moving from the view of a routed component to elements in different components like a matMenu and an input field, the routed component seems to refresh itself. This becomes p ...

Retrieve values from DynamoDB in their original Number or String formats directly

Here is the code I am using to retrieve data from DynamoDB. async fetchData(params: QueryParams) { return await this.docClient.send(new QueryCommand(params)); } const dbObject: QueryParams = { TableName: process.env.TABLE_NAME, KeyCo ...

When using Angular's npm, an underscore is added to an already existing directory within angular-devkit, resulting in a "directory not found" (ENOENT) error

Encountered an error while compiling my Angular Electron app that states Error: ENOENT: no such file or directory, open 'node_modules/@angular-devkit/build-angular/src/angular-cli-files/_models/webpack-configs/browser.js'. Despite the error messa ...

The parameter of type '{ userInfo: string | null; }' cannot be assigned to type 'never' in this argument

Currently, I am working on creating a context API in React using TypeScript to store user details and tokens. Since I am relatively new to TypeScript, I am facing some challenges understanding the errors below. Can someone please assist me with this? ..... ...

Understanding how to retrieve the Request Header value when entering my Angular application

My Angular application needs to be accessed from another external or internal application. The request sent from this application includes specific information in the Request Header that I need to identify where it is coming from. However, I am strugglin ...

"Encountered an error while trying to access the 'get' property of an undefined object in Angular 7 Forms

I encountered an issue while working on Angular 7 forms. The built-in validation for the form functioned flawlessly, but when attempting to implement custom validation by creating a custom function, I faced an error related to the userpass field. My intent ...

The TypeScript 'object' type

My query regarding the definition of TypeScript's {} type has brought about some confusion. Initially, I believed it represented an "empty object with no properties," but I recently encountered an ESLint rule that prohibits the use of {} type because ...

Troubleshooting the problem of redirecting a website to www on IIS 10 (Windows Server 2019)

I have a React website running on port 3000. Currently, the website can be accessed with and without the www prefix, causing duplicate SEO issues. I want to ensure that the website always redirects to https://www.pess.org.ua. web.config <?xml version=& ...