Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 patchValue push value into array

Is it It looks like Angular2's FormGroup.patchValue() doesn't push new elements into an array.

For example something like this:

ngOnInit() {

    this.form = this.formBuilder.group({
        animal: [''],
        school: this.formBuilder.group({
            name: [''],
        }),
        students: this.formBuilder.array([this.formBuilder.control('Bob')])
    });

    setTimeout(() => this.form.patchValue({
      animal: 'cat'
      school : {name: 'Fraser'},
      students: ['Bob gets edited', 'This will not show']
    }), 250);

}

Will only update the first element in "students" but it will not insert the second element.

What would I need to do to make it display both elements?

Plunker here.

like image 282
Chi Chan Avatar asked Dec 01 '16 16:12

Chi Chan


3 Answers

Well, as silentsod said, it is not possible. Currently, I am using below as an alternative:

        let controlArray = <FormArray>this.form.controls['apps'];           
        this.list.forEach(app => {
                    const fb = this.buildGroup();
                    fb.patchValue(app);
                    controlArray.push(fb);
            });

Angular Team - We need a new function something like PatchArray() that would patch from a collection/object graph. It is a basic use case.

like image 52
Manish Jain Avatar answered Nov 19 '22 12:11

Manish Jain


.patchValue() only updates the existing FormArray, it won't modify the structure of your form model.

patchValue(value: any[], {onlySelf, emitEvent}?: {onlySelf?: boolean, emitEvent?: boolean}) : void Patches the value of the FormArray. It accepts an array that matches the structure of the control, and will do its best to match the values to the correct controls in the group.

It accepts both super-sets and sub-sets of the array without throwing an error.

You actually need to push a new element onto the array in order for it to appear.

 this.form.controls['students'].push(new FormControl('This will not show'));

This is all in the FormArray documentation https://angular.io/docs/ts/latest/api/forms/index/FormArray-class.html

like image 40
silentsod Avatar answered Nov 19 '22 13:11

silentsod


Well, the solution I found out is:

this.myForm.controls['array'] = this.formBuilder.array(newArray.map(i => this.formBuilder.group(i)));
like image 7
Giovane Avatar answered Nov 19 '22 13:11

Giovane