【问题标题】:Cannot find control with unspecified name attribute (formArray)找不到具有未指定名称属性的控件 (formArray)
【发布时间】:2020-09-01 20:17:31
【问题描述】:

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

这是我的代码:

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>

【问题讨论】:

  • IMK,当我们有 [formGroup] 时,我们传递 [formControlName] 而不是实际控件,我们让 angular 选择控件本身。

标签: angular formarray


【解决方案1】:

问题是您使用 [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>

【讨论】:

  • 谢谢你,我已经通过删除 div 中的 [formControl] 解决了这个问题,但你的解决方案使它更加干净。
猜你喜欢
  • 2019-06-17
  • 1970-01-01
  • 2020-04-05
  • 2019-07-04
  • 1970-01-01
  • 1970-01-01
  • 2018-05-28
  • 2018-12-05
  • 2017-09-12
相关资源
最近更新 更多