【问题标题】:not able to iterate on FormArray无法在 FormArray 上进行迭代
【发布时间】:2021-10-08 18:24:36
【问题描述】:

我正在使用的方法 -- 表单组 -- -- FormControl -- , -- FormArray -- ----------------- -- FormControlList --

我也尝试过嵌套表单组中的 FormArray

但我无法迭代表单数组,如果方法正确,请告诉我。

HTML 错误--:对象可能为“空”- 控件

代码 -

HTML --
<form [formGroup]="abcForm">
    <section>
<div formArrayName="title">
<ul>
  <li *ngFor="let control of abcForm.get('title').controls; let i= index;">
       {{i}}
  </li>
</ul>
</div>
</form>

///////////////////

TS --

titles: any = [
    {
      name: "one",
      value: "one",
      selected: false
    },
    {
      name: "two",
      value: "two",
      selected: true
    },
    {
      name: "three",
      value: "three",
      selected: true
    },
  ];

constructor(private fb: FormBuilder)
this.abcForm = this.fb.group({
      one: ['',Validators.required],
      title:
        this.buildTitleControls()
      ,
    });

buildTitleControls() {
    const arr = this.titles.map((val : any) => {
      return this.fb.control('');
    });
    return this.fb.array(arr);
  }

【问题讨论】:

    标签: angular angular-material


    【解决方案1】:

    您必须将? 添加到abcForm.get('title')

    <li *ngFor="let control of abcForm.get('title')?.controls; let i= index;">
    

    【讨论】:

      【解决方案2】:

      只需在表单上放一个 *ngIf:

      &lt;form [formGroup]="abcForm" *ngIf="abcForm"&gt;

      它在你的 formGroup 完成初始化之前呈现。

      【讨论】:

        【解决方案3】:

        您可以为title 编写一个getter,以将控件检索为FormArray

        对于 HTML,请使用 title.controls

        get title(): FormArray {
          return this.abcForm.controls['title'] as FormArray;
        }
        
        <li *ngFor="let control of title.controls; let i = index">
          {{ i }}
        </li>
        

        Sample Solution on StackBlitz

        【讨论】:

          猜你喜欢
          • 2018-08-29
          • 1970-01-01
          • 2014-03-11
          • 1970-01-01
          • 2019-10-22
          • 1970-01-01
          • 2022-11-27
          • 2021-01-06
          • 1970-01-01
          相关资源
          最近更新 更多