Angular6:设置空表单数组字段

Angular 6: Set empty form array field

我正在使用 Angular 6。和 Reactive form builder 构建表单。

ngOnInit() {
    this.landingPageForm = this.formBuilder.group({
      title: new FormControl('', [
        Validators.required
      ]),
      description: new FormControl('', [
        Validators.required
      ]),
      faqs: this.formBuilder.array([
        this.createFaqFields()
      ]),
    });

    this._setFormValue();
}

createFaqFields(): FormGroup {
  return this.formBuilder.group({
    question: new FormControl(),
    answer: new FormControl()
  });
}

private _setFormValue() {
    if (this.product) {
      this.landingPageForm.setValue({
        title: this.product.info.title,
        description: '',
        faqs: [],
      });
    }
  }

我最初必须预填充几个字段,faqs 是一个数组字段,其中通过调用

动态生成新字段
onClickAddFaqField(): void {
  this.faqFields = this.landingPageForm.get('faqs') as FormArray;
  this.faqFields.push(this.createFaqFields());
}

最初,HTML 中只有一个常见问题解答输入字段,而且该字段为空。但它给出了一个错误

"Must supply a value for form control at index: 0.

如何将数组输入字段初始化为空?

我想,我会这样做:

ngOnInit() {
  this.landingPageForm = this.formBuilder.group({
    title: new FormControl('', [Validators.required]),
    description: new FormControl('', [Validators.required]),
    faqs: this.formBuilder.array([])
  });

  // Try this
  // OTOH why when you set that to [] in _setFormValue()?
  this.landingPageForm.get('faqs').push(this.createFaqFields());

  this._setFormValue();
}

createFaqFields(): FormGroup {
  return new FormGroup({
    question: new FormControl(null),
    answer: new FormControl(null)
  });
}

不要在 createFaqFields() 中使用 FormControl(),而是像这样尝试,

ngOnInit() {
      this.landingPageForm = this.formBuilder.group({
        title:'',
        description: '',
        faqs: this.formBuilder.array([this.createFaqFields()])
      });
        this._setFormValue();
    }


    createFaqFields(): FormGroup {
      return this.formBuilder.group({
        question: '',
        answer: ''
      });
    }

在尝试了来自不同来源的所有答案和示例之后。我就是这样解决的。

private _setFormValue() {
  if (this.product) {
    this.landingPageForm.setValue({
      title: this.product.info.title,
      description: '',
      faqs: [{
        question: '',
        answer: ''
      }],
    });
  }
}

已将 question, answer 添加为空值作为 faqs 字段的第一个对象。