简体   繁体   English

Angular 4:setValue formBuilder 空数组

[英]Angular 4: setValue formBuilder empty array

I have such 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 some more memes :稍后我可以添加更多memes

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

and then if i get form values i get:然后如果我得到表单值,我会得到:

this.form.controls['memes'].value - here i have array this.form.controls['memes'].value - 这里我有数组

But there is a case, when i need this this.form.controls['memes'].value to set to an empty array, how is it possible to do?但是有一种情况,当我需要将此this.form.controls['memes'].value设置为空数组时,怎么办?

If i set it this way:如果我这样设置:

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

I got error: Must supply a value for form control at index: 0.我收到错误: Must supply a value for form control at index: 0.

what i do wrong?我做错了什么?

EDIT:编辑:

As of newer versions, Angular now supports clearing a FormArray with clear() :从新版本开始,Angular 现在支持使用clear()清除FormArray

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

ORIGINAL:原文:

Tried a few things: reset() , setControl() , but the following was the only solution I found to work that actually resets the whole array to [] , other options worked, but they left the formgroups in place, just emptied the values.尝试了几件事: reset()setControl() ,但以下是我发现的唯一可行的解​​决方案,它实际上将整个数组重置为[] ,其他选项有效,但他们将表单组留在原地,只是清空了值.

So how I got it to work, was to iterate the form array and delete each form group with that particular index in the loop:所以我如何让它工作,是迭代表单数组并删除循环中具有该特定索引的每个表单组:

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

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

If there is a better way, I'm open for suggestions!如果有更好的方法,我愿意接受建议! :) :)

Try this.myForm.controls['myFormArray'] = this.formBuilder.array([]);试试this.myForm.controls['myFormArray'] = this.formBuilder.array([]); with formBuilder service instantiated in your constructor.在构造函数中实例化了 formBuilder 服务。

FORM形式

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

1st method第一种方法

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

2nd method方法二

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

我遇到了类似的问题,在更新表单后我会收到上述错误,经过大量调查和失败的实验,我发现this.myForm.updateValueAndValidity终于成功了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM