How to data bind to a Form Group within a Form Array? Angular

Kevin

I am trying to make an Angular Forms app that allows the user to input some information. The user will be required to fill basic information and add two sets of skills to the form at a time and add these are stored in array..

HTML:

<div class="form-container">
  <form (ngSubmit)="submit()" [formGroup]="myForm">
    <h1>User Registration</h1>
    <div class="form-group">
      <label for="firstname"></label>`
      <input type="text" name="firstname" formControlName="name" />
      <input type="text" name="firstname" formControlName="email" />
      <div formArrayName="skills">
        <ng-container *ngFor="let skill of skillsArray.controls; index as i">
        <div formGroupName="skills">      
          <input
            type="text"
            name="firstname"
            placeholder="my skill"
            formControlName="name"
            formControlName="first_skill"
          />
          <input
          type="text"
          name="firstname"
          placeholder="my skill"
          formControlName="name"
          formControlName="second_skill"
        />
        </div>
          <button (click)="addSkills()">Add Skills</button>
        </ng-container>
      </div>
      <button type="submit">Submit</button>
    </div>

    <br />
<div class="form-check">


    {{ myForm.value | json }}
    <br />
    {{ myForm.valid | json }}
</div>
  </form>
</div>

TS:

export class FormCompComponent implements OnInit {
  myForm!: FormGroup;

  constructor (private fb : FormBuilder) {

  }

  ngOnInit(): void {
    this.myForm = new FormGroup({
      name: new FormControl('', Validators.required),
      email: new FormControl('', Validators.required),
      skills: new FormArray([
        new FormGroup({
          first_skill: new FormControl('', Validators.required),
          second_skill: new FormControl('', Validators.required),

        })
      ]),
    });

  }



  addSkills() {
    this.skillsArray.push(new FormControl('', Validators.required));
  }

  get skillsArray() {
    return this.myForm.get('skills') as FormArray;
  }

  submit() {
    console.log(this.myForm.value);
  }
}

 

From an interface perspective, everything is okay, I am able to add items to the array successfully but I am struggling to bind my input to my typescript objects

These are my results when inputting:

{ "name": "test", "email": "test", "skills": [ { "first_skill": "", "second_skill": "" }, "" ] }

How do i penetrate the nested objects from my HTML?

I am currently looping over the array and then attempting to access formGroupName.

My inputs register as blank. why is this?

Thanks,

Yong Shun

Issue 1: Incorrectly add FormGroup into FormArray

From here:

addSkills() {
  this.skillsArray.push(new FormControl('', Validators.required));
}

You are adding FormControl into skills FormArray, it supposes to be adding the FormGroup instead.

Solution for Issue 1

  1. Would suggest writing a function for generating FormGroup for the skill object (initSkillFormGroup method).

  2. Call the initSkillFormGroup method and add it to skillsArray.

addSkills() {
  this.skillsArray.push(this.initSkillFormGroup());
}

initSkillFormGroup() {
  return new FormGroup({
    first_skill: new FormControl('', Validators.required),
    second_skill: new FormControl('', Validators.required),
  });
}
  1. (Optional) Writing the initSkillFormGroup method to avoid redundant declaring the FormGroup for skill object. Well, when you build the root form, you can initialize the skills FormArray by calling the mentioned function.
this.myForm = new FormGroup({
  ...,
  skills: new FormArray([this.initSkillFormGroup()]),
});


Issue 2: Incorrectly generate each skill FormGroup in skills FormArray

Solution for Issue 2

Pass the i to [formGroupName] attribute.

<ng-container *ngFor="let skill of skillsArray.controls; index as i">
  <div [formGroupName]="i">
    ...
  </div>
</ng-container>

Demo @ StackBlitz

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

bind an array of data to form array in angular

How to bind data to a mat form field in angular?

how to get data in form of array in mongoose group

How to bind form group to nested dynamically created components in Angular

Bind Array Data with the Reactive Form

How to bind angular dynamic form?

Bind JSON Array to a Nested Form Group

How to Angular form data added to model array?

How to get all data in form Array in angular?

how to bind data in reactjs form

Pass data in Angular Form Group

How to bind nested object within Form?

How to bind web api data to form select option in Angular 6

How to bind data that come from database into angular dynamic form dropdown?

Can't bind nested form group to form array in reactive Forms?

How to group form data with Vue

Fetching data to Angular Form Array

How to access form control and form group in angular reactive form

How do I bind data using ng-model with ng-repeat ( within a form )

How to bind angular form validation with ngFor

How to bind a array form field with Playframework scala

Form array of form group , get changes for exact specific control - angular

angular 5 set value to nested form group form array

Looping through form array inside form group angular

Angular Form Array - Dynamically Add Value to Nested Form Group

how to bind data to list in spring form

how to bind form data to list<object>

In an Angular 7 application, with reactive forms, how can i modify this method so that it will clear only invalid form controls within a form group?

Zend with Sub Forms returning subform as an array within array form data, how to return a single array?

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive