找不到具有未指定名称属性的控件 (formArray)

Cannot find control with unspecified name attribute (formArray)

大家好,我正在尝试构建一个具有 formArray 的 rective 表单,我希望能够动态添加或删除输入字段,但我收到错误消息: 找不到具有未指定名称属性的控件

这是我的代码:

ts 文件:

@Component({
 selector: 'app-create-ilm-policy',
 templateUrl: './create-ilm-policy.component.html',
 styleUrls: ['./create-ilm-policy.component.scss']
})

export class CreateIlmPolicyComponent implements OnInit {

    mainForm:FormGroup

    constructor(){}

    get patterns(){
    return <FormArray>this.mainForm.get('indexPatterns')
    }

    ngOnInit(): void {
      this.mainForm = new FormGroup({
       indexPatterns: new FormArray([this.addIndexPattern()]),
       rolloverAlias: new FormControl()
      })
    }

     addIndexPattern(): FormControl{
     return new FormControl()
     }

     removeIndexPatternRow(index: number) {
     (<FormArray>this.mainForm.get('indexPatterns')).removeAt(index)
     }

     addIndexPatternRow(){
     (<FormArray>this.mainForm.get('indexPatterns')).push(this.addIndexPattern())
     }
}

html 文件:

<form [formGroup]="mainForm">
<div formArrayName="indexPatterns" *ngFor="let pattern of patterns.controls; index as i">

      <div class="d-flex align-items-center" [formControl]="i">

        <mat-form-field appearance="fill">
          <mat-label>modèle d'indices</mat-label>
          <input matInput [formControl]="patterns.controls[i]"> <!--line that throws the error!!!!!!!-->
          <mat-hint>ajouter * à la fin</mat-hint>
        </mat-form-field>

        <mat-icon class="pointer" color="warn" (click)="removeIndexPatternRow(i)" svgIcon="delete_forever" aria-hidden="false"></mat-icon>

      </div>
    </div>
</form>

问题是您正在使用 [formControl] 设置名称,而 FormArray 使用索引作为名称,应该使用 [formControlName]

定义
<form [formGroup]="mainForm">
  <div formArrayName="indexPatterns" *ngFor="let pattern of patterns.controls; index as i">
    <div class="d-flex align-items-center">
      <mat-form-field appearance="fill">
        <mat-label>modèle d'indices</mat-label>
        <input matInput [formControlName]="i" />
        <!--line that throws the error!!!!!!!-->
        <mat-hint>ajouter * à la fin</mat-hint>
      </mat-form-field>

      <!-- <mat-icon
        class="pointer"
        color="warn"
        (click)="removeIndexPatternRow(i)"
        svgIcon="delete_forever"
        aria-hidden="false"
      ></mat-icon> -->
    </div>
  </div>
</form>