Angular 4: setValue formBuilder empty array

I have such a reactive form:

constructor(...){
  this.form = this.formBuilder.group({
    name: ['', Validators.compose([Validators.required, Validators.maxLength(50)])],
    memes: this.formBuilder.array([
      this.initMemes('TrollFace')
    ])
  });
}

initMemes (name?) {
  return this.formBuilder.group({
    id: [''], name: [name]
  });
}

later I can add more memes:

addMemes () {
  const control = <FormArray>this.form.controls['memes'];
  control.push(this.initMemes('anyName'));
}

and then if I get the values ​​of the form, I get:

this.form.controls['memes'].value - here I have an array

But is there a case where I need this to this.form.controls['memes'].valueset an empty array, how can this be done?

If I installed it like this:

this.form.controls['memes'].setValue([])

I got an error: Must supply a value for form control at index: 0.

what am I doing wrong?

+7
source share
4 answers

EDIT:

Starting with newer versions, Angular now supports cleanup FormArraywith clear():

(<FormArray>this.form.get('memes')).clear();

ORIGINAL:

: reset(), setControl(), , , [], , , .

, , :

const control = <FormArray>this.form.controls['memes'];

for(let i = control.length-1; i >= 0; i--) {
  control.removeAt(i)
}

, ! :)

+7

this.myForm.controls['myFormArray'] = this.formBuilder.array([]); formBuilder, .

+7

FORM

this.form = this._formB.group({
    blocks: this._formB.array([])
});

1-

let fArray = <FormArray>this.form.controls['blocks'];
while (fArray.length !== 0) {
  fArray.removeAt(0)
}

this.form.setControl('blocks', this._formB.array([]));
+5

, , , this.myForm.updateValueAndValidity, , .

+1

All Articles