Initialize an array of forms without empty input with index 0

I am currently creating updating, adding, deleting and editing forms using angular 2 and reactive forms. I grouped the controls into an array of form forms to dynamically add input controls to the array of forms. This works great for an empty form that has no elements to initialize.

export class ItemsPage{

   collectionForm: FormGroup;
   get items(): FormArray { return <FormArray>this.collectionForm.get('items'); }

   constructor(public formBuilder: FormBuilder){

        this.pageDetails = this.navParams.data;

        this.collectionForm = this.formBuilder.group({
           items: this.formBuilder.array([this.buildItem()])
        });
   }

   buildItem(item?: string): FormGroup {
       return this.formBuilder.group({ item: [item || '', Validators.required] });
   }

   ionViewDidLoad() {
       // Builds a form with pre populated items 
       forEach(this.pageDetails, value => {
           this.items.push(this.buildItem(value));
       })
   }
}

The problem is that the list of controls in the view contains empty input in index 0when it this.pageDetailshas a list of values. This can be removed in constructorwith

this.items.removeAt(0);

However, this does not seem to be correct. I thought that maybe I could build an array informBuilder.array

let prebuildItems = forEach(this.pageDetails, value => { // lodash forEach
  this.items.push(this.buildItem(value));
});

this.collectionForm = this.formBuilder.group({
  items: this.formBuilder.array([prebuildItems])
});

However, when I go to the page with this code, I get the following error:

. /ItemsPage class ItemsPage - : 'get' undefined

+4
1

, ( FormArray).

addHeader(name = '', value = '') {
    // get headers array control from group
    let headers = <FormArray>this.editForm.controls['options'].controls['headers'];

    // create new header control
    let header = this.fb.group({
        name: [name, Validators.required],
        value: [value]
    });

    // set the value on the control
    // header.setValue({ name, value });

    // add the new control to the array
    headers.push(header);
}

, , .

this.data.headers.forEach(h => {
    this.addHeader(h.name, h.value);
});

Angular Reactive Forms "secretLairs" FormArray

, , , , ,

this.formBuilder.array([this.buildItem()])

"" , .

+3

Source: https://habr.com/ru/post/1673479/


All Articles