Array of Angular FormGroup

I am facing an issue with setting data to the form array in my project. The scenario is that when filling out user details, some users have multiple addresses.

Here is User.ts

export interface User {
  id?: number;
  name: string;
  age: number;
  address: MyAddress;
}

MyAddress.ts

export interface MyAddress {
  id?: number;
  line1: string;
  line2: string;
  postalCode: string;
  city: string;
}

Inside component.ts file

myForm = this.formBuilder.group({
    name: ['', Validators.required],
    age: ['', Validators.required]
});

myFormAddress = this.formBuilder.group({
    address: this.formBuilder.array([]),
});

setDetail(): User {
    let myObj = new User();
    myObj.name = this.myForm.controls.name.getRawValue();
    myObj.age = this.myForm.controls.description.getRawValue();
    
    myObj.address = {
      //need to set form array data here
    }
    
    return myObj;
  }

Answer №1

Using a single formGroup is sufficient:

studentForm = this.formBuilder.group({
    firstName: ['', Validators.required],
    lastName: ['', Validators.required],
    grades: this.formBuilder.array([]),
});

Answer №2

Incorporate the capability for multiple addresses in your User interface:

export interface User {
  id?: number;
  name: string;
  age: number;
  address: MyAddress[];
}

Ensure that address is included in myForm:

myForm = this.formBuilder.group({
  name: ['', Validators.required],
  age: ['', Validators.required],
  address: this.formBuilder.array([]),
});

You can then access the array similar to a regular form control:

myObj.address = this.myForm.controls.address.getRawValue();

Alternatively, retrieve the entire object from the form value directly:

myObj = this.myForm.value as User;

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

Mat-dialog not filtering JSON data properly due to filter buttons not combining logic

I'm currently working on developing a filter component, and I've encountered an issue. When I select both Buy it Now and Private Auction options, they function independently but not together. If an item has both Buy It Now and Private Auction ena ...

Attempt the initial request using the HttpInterceptorFn feature in Angular 17 (Functional HTTP Interceptor)

I'm encountering an issue with my interceptor when it intercepts a request based on JWT expiration. I can successfully refresh the token, but the original request is not retried. My error interceptor works well except for the retrying of the original ...

Implementing angular-material-design into an Angular 4 application with the help of Angular CLI

Is there a proper way to use bootstrap-material-design in an Angular 4 app with Angular CLI? In my project, I included the css file in my styles.css like this: @import "~bootstrap-material-design/dist/css/bootstrap-material-design.min.css"; Although I c ...

Adding data structure to Mongoose

I currently have two collections: one for users and another for cats. My goal is to have the data for cats stored under my users collection, but I am encountering some difficulties. User.js var Schema = mongoose.Schema; var userSchema = Schema({ _id: Sch ...

Tips for retrieving the first true value in an *ngIf statement within an *ngFor loop

I have an array of items that must be shown based on different roles. I am looking for the first item in the array that meets the ngIf condition. Below is my code snippet: This is how my Array initially looks: parentTabList = [ { nam ...

Angular: one-time token refresh

Currently, I am utilizing the JWT with refresh token strategy for authentication and have implemented an interceptor in my Angular client to send the token as a header. Before sending any requests, I ensure to check for expiration and refresh the token us ...

Confusion arises from the error message 'No overload matches this call'

Currently, I am working on a weather application using Angular based on the concepts from the book Angular for Enterprise-Ready Web Applications - Second Edition. I am in the process of adding a search component to the app, which will allow users to displa ...

Eslint highlighting the initial function declaration within a Vue script

I'm currently creating a Vue file using a Typescript script, and encountering an unusual Eslint "error." https://i.sstatic.net/UXv3A.png The issue arises on line 15 with this specific complaint: Parsing error: Unexpected token, expected "," Interes ...

Having trouble retrieving the value of a service within the @CanActivate decorator in the component

I am currently utilizing Angular 2.0.0-beta.15 and I am attempting to implement @CanActivate in the component. The code snippet below showcases my attempt: @CanActivate((next: ComponentInstruction, previous: ComponentInstruction) => { console.log(&ap ...

Error message "System is not defined when compiling with the --outFile flag" is displayed

I am facing a perplexing issue: why does the following error occur when compiling with typescript using the --outFile flag?: ReferenceError: System is not defined This error only arises during the bundling process. I have been searching for a solution bu ...

Working with Angular: How to group multiple ng-templates and display or hide them based on conditions

There is a structure on a view that looks like this: <ng-template '#body'> <div *ngif="isAnswerA; else answerB"> <section>... </section> </div> <ng-template '#answerB'> <section>... </secti ...

Extracting arrays from JSON in Angular: A step-by-step guide

I am currently working with Angular2 (version 5) and facing an issue. I am able to make an HTTP request and receive JSON data. While I know how to access and use individual values, I am struggling with accessing and extracting the two arrays inside an elem ...

Using FormArrays with ControlValueAccessor in Angular

Is there a way to pass the formArray down to a child article component? The article component does not contain a FormGroup (which is defined in the parent) and I am encountering an error: Error: formArrayName must be used with a parent formGroup directive ...

Generating ng2 chart data dynamically within Angular 4

In my latest project, I've developed an application that retrieves data from a service in JSON format and displays it on a UI chart. However, I've encountered a recurring issue where the data does not bind properly to the chart despite multiple ...

Custom navigation button in Angular's FullCalendar header

In my Angular project, I am utilizing fullcalendar with both week and month views, and it has been working smoothly so far. Now, my aim is to modify the text displayed on the navigation button. As per the documentation, I have created custom buttons as fo ...

Struggling to incorporate a pause decorator into my application, I encountered difficulties while trying to understand a related issue

I am currently working with a service file that contains the following: export class MockDataService { data:[] = []; getAll(): Observable<any[]> { return of(this.data); } } To introduce a delay to my mocks, I decided to use a @pause() decora ...

How can you identify when an input value has been modified in Angular?

For my current project, I am developing a directive to be used with a text input field in order to format currency input. This directive has two HostListeners - one for when the input loses focus and one for when it gains focus. When the blur event occurs, ...

Is React Spring failing to trigger animations properly on iOS devices?

I have a code that functions perfectly on my desktop and across all browsers. Each button is designed to trigger a 4-second animation upon load or hover, initiating the playback of various videos. However, there's an issue with iOS where the video or ...

Unable to run 'ng serve -o', however 'ng serve' functions correctly

Encountering an issue with Angular when attempting to configure the Micro frontend Framework (module federation) for both the remote and host applications. They are not located in the same workspace. When running the remote app with "ng serve -o", an error ...

The "Selected" option does not function properly within Angular's reactive form implementation

I am facing an issue with my dropdown menu where I want the first option to be selected by default, but it is not working as expected. I suspect that the problem lies in how I initialized the control with a default undefined value in the .ts file. Even whe ...