【问题标题】:getting controls inside nested formArray在嵌套的 formArray 中获取控件
【发布时间】:2021-03-07 21:13:52
【问题描述】:

我想知道如何在嵌套的 formArray 中获取控件。我初始化了这个表单

 ngOnInit(): void {
     this.surveyForm = this.formBuilder.group({
       'surveyTitle': [null],
       'surveyDescription': new FormControl(null),
       'questionsDetail': this.formBuilder.array([
         this.formBuilder.group({
          'questionType': new FormControl('mcq'),
           'question': new FormControl(null),
           'choices': this.formBuilder.array([])
         })
       ])
     });

但是当我尝试访问我的选择 formArray 的控件时,我得到一个错误。我用了这段代码

get questionsDetailcontrols() {
    return (this.surveyForm.get('questionsDetail') as FormArray).controls;
  }
  get choicesControl()
  {
    return (this.questionsDetailcontrols.get('choices') as FormArray).controls;
  }

我在 get('choices') 中收到错误消息,指出“在类型 'AbstractControl[]' 上不存在属性 'get'”。 谁能告诉我如何访问嵌套数组中的控件。

提前致谢

【问题讨论】:

    标签: angular formbuilder formarray


    【解决方案1】:

    试试这个。

      get questionsDetailcontrols() {
        return this.surveyForm.get('questionsDetail') as FormArray;
      }
    
      getChoicesControl(index: number)
      {
            return (this.questionsDetailcontrols.at(index).get('choices') as FormArray).controls;
      }
    

    【讨论】:

    • 我仍然收到错误消息。实际上它是相同的错误,但指向 at()。
    • 我已经更新了我的答案。从questionsDetailcontrols中删除.controls就可以了
    • 它的工作谢谢你我做了一些改变。 getchoicesControl(index:number) { return (this.questionsDetailcontrols.at(index).get('choices') as FormArray).controls; }
    • getter、choicesControl 怎么会在这里接受参数?
    • 它不是一个getter,而是一个函数
    猜你喜欢
    • 2020-09-27
    • 2021-10-16
    • 2017-11-09
    • 1970-01-01
    • 2018-02-08
    • 2019-04-21
    • 2018-07-15
    • 1970-01-01
    • 2021-09-16
    相关资源
    最近更新 更多