question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Add support for undefined number of items of form builder array

See original GitHub issue
  • bug report => search github for a similar issue or PR before submitting
  • feature request
  • support request => Please do not submit support request here, instead see

When using form builders in a reactive form, it is impossible to create an array of objects with an undefined number of objects. Let’s say I have this form:

this.form = this.formBuilder.group({
    persons: this.formBuilder.array([
          this.formBuilder.group({
                name: [''],
                job: ['']
          })
    ]),
})

If my array is:

var personsArray= [{name:'John', job:'plumber'}, {name:'Jack', job:'engineer'}, {name:'Bob', job:'cook'}];

I can’t really patch the form like this:

this.form.patchValue({persons: personsArray})

because it will only batch the first item of the array. There should be a way to iterate over the form array to create these controls through the patchValue function…

Issue Analytics

  • State:open
  • Created 7 years ago
  • Reactions:8
  • Comments:11 (5 by maintainers)

github_iconTop GitHub Comments

6reactions
nellyigieborcommented, Mar 17, 2017

Hi,

I need help creating “reactive form builder array” from the below json data ( master --> detail wtih detail )

{ “docNo”: “abc0001”, “transactionsDate”: “01/01/2017”, “storeId”: “abcd”, “invoiceDispatchDate”: “01/01/2017”, “deliveryAddress”: “abc street, abc qtrs…”, “purchaseDetail”: [ { “modelName”: “abc leather”, “price”: “70$”, “quantityDetail”: [ { “colorDetail”: [ { “colorName”: “Black”, “quantity”: [ { “sizeNo”: “11”, “quantity”: 12 }, { “sizeNo”: “12”, “quantity”: 10 }, { “sizeNo”: “10.5”, “quantity”: 200 } ] }, { “colorName”: “Red”, “quantity”: [ { “sizeNo”: “11.5”, “quantity”: 120 }, { “sizeNo”: “11”, “quantity”: 50 }, { “sizeNo”: “12”, “quantity”: 20 } ] } ] } ] } ] }

Thanks in advance.

Nelly

1reaction
Tiedyecommented, Feb 28, 2019

I put together a component for my own project which fill in this gap (barely tested, just experimenting atm)

import { FormArray, AbstractControl, ValidatorFn, AbstractControlOptions, AsyncValidatorFn } from '@angular/forms';


export class FormArrayTemplate extends FormArray {
  constructor(
    public factory: (value: any, i: number) => AbstractControl,
    validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null,
    asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null
  ) {
    super([], validatorOrOpts, asyncValidator);
  }

  private _fixLength(value: any[]) {
    const length = value.length;
    if (this.length < length) {
      for (let i = this.length; i < length; ++i) {
        const control = this.factory(value[i], i);
        this.controls.push(control);
        (this as any)._registerControl(control);
      }
    } else if (this.length > length) {
      for (let i = this.length - 1; i >= length; --i) {
        (this.controls[i] as any)._registerOnCollectionChange(() => {});
      }
      this.controls.splice(length);
    }
  }

  patchValue(value: any[], options: {onlySelf?: boolean, emitEvent?: boolean} = {}) {
    this._fixLength(value);
    super.patchValue(value, options);
  }

  setValue(value: any[], options: {onlySelf?: boolean, emitEvent?: boolean} = {}) {
    this._fixLength(value);
    super.setValue(value, options);
  }

  reset(value: any = [], options: {onlySelf?: boolean, emitEvent?: boolean} = {}) {
    this._fixLength(value);
    super.reset(value, options);
  }
}

Since it extends FormArray it can be used anywhere a FormArray is expected (including in a FormBuilder)

Read more comments on GitHub >

github_iconTop Results From Across the Web

Form Control in form array is undefined - Stack Overflow
First of all you are missing the ATests getter. You have to push something FormGroup or FormControl in your FormArray .
Read more >
FormArray - Angular
Tracks the value and validity state of an array of FormControl ... Default is undefined . ... Set the values for the controls...
Read more >
Angular FormArray - Complete Guide
Actually, a FormArray can have an undetermined number of form controls, starting at zero! The controls can then be dynamically added and removed ......
Read more >
How to Use Angular FormArray(s) within FormGroup(s) In ...
Make sure to add FormsModule and ReactiveFormsModule to your imports. Now let's create our initial form. Here I will be using FormBuilder.
Read more >
Indexed collections - JavaScript - MDN Web Docs - Mozilla
This chapter introduces collections of data which are ordered by an index value. This includes arrays and array-like constructs such as ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found