Angular 2 在 formArrays 上找不到具有未指定名称属性的控件

Angular 2 Cannot find control with unspecified name attribute on formArrays

我正在尝试遍历组件中的 formArray,但出现以下错误

Error: Cannot find control with unspecified name attribute

这是我的 class 文件中的逻辑

export class AreasFormComponent implements OnInit {
    public initialState: any;
    public areasForm: FormGroup;

    constructor(private fb: FormBuilder) { }

    private area(): any {
      return this.fb.group({
          name: ['', [Validators.required]],
          latLong: ['', [Validators.required]],
          details: ['', [Validators.required]]
      });
    }

    public ngOnInit(): void {
        this.areasForm = this.fb.group({
            name: ['', [Validators.required]],
            areas: this.fb.array([this.area()])
        });
    }
}

和我的模板文件

<form class="areas-form" [formGroup]="areasForm" (ngSubmit)="onSubmit(areasForm.values)">
    <md-input-container class="full-width">
        <input mdInput placeholder="Location Name" type="text" formControlName="name" required>
        <md-error *ngIf="areasForm.get('name').hasError('required')">Please enter the locationName</md-error>
    </md-input-container>
    <md-grid-list cols="1" [formArrayName]="areas">
        <md-grid-tile formGroupName="i"  colspan="1" rowHeight="62px" *ngFor="let area of areasForm.controls.areas.controls; let i = index ">
            <md-grid-list cols="3" rowHeight="60px">
                <md-grid-tile colspan="1">
                    <md-input-container class="full-width">
                        <input mdInput placeholder="Area Name" type="text" formControlName="name" required>
                        <md-error *ngIf="areasForm.get('areas').controls[i].name.hasError('required')">Please enter the area name</md-error>
                    </md-input-container>
                </md-grid-tile>
                <md-grid-tile colspan="1">
                    <md-input-container class="full-width">
                        <input mdInput placeholder="details" type="text" formControlName="details" required>
                        <md-error *ngIf="areasForm.get('areas').controls[i].name.hasError('required')">Please enter the locationName</md-error>
                    </md-input-container>
                </md-grid-tile>
                <md-grid-tile colspan="1">
                    <button md-fab (click)="remove(i)"><md-icon>subtract</md-icon>Remove Area</button>
                </md-grid-tile>
            </md-grid-list>
        </md-grid-tile>
    </md-grid-list>
    <button type="submit" [disabled]="areasForm.invalid" md-raised-button color="primary">Submit</button>
</form>

而不是

formGroupName="i"

您必须使用:

[formGroupName]="i"

提示:

由于您循环控制,您已经有了变量 area,因此您可以替换它:

*ngIf="areasForm.get('areas').controls[i].name.hasError('required')"

作者:

*ngIf="area.hasError('required', 'name')"

删除

中的括号
[formArrayName]="areas" 

并且仅使用

formArrayName="areas"

这是因为 [ ] 您试图绑定一个 变量 ,但事实并非如此。还要注意你的提交,它应该是:

(ngSubmit)="onSubmit(areasForm.value)"

而不是 areasForm.values

我的问题是我有

[formControlName]=""

而不是

formControlName=""

在我的例子中,我通过将 formControl 的名称放在双引号和单引号中以便将其解释为字符串来解决问题:

[formControlName]="'familyName'"

类似于以下内容:

formControlName="familyName"

这件事发生在我身上,因为我在

某处有 fromArrayName 而不是 formArrayName

对我来说,我试图添加 [formGroupName]="i" and/or formControlName 忘记指定父 formArrayName。注意你的表单组树。

这发生在我身上,因为我将 formControlName 留空 (formControlName="")。因为我不需要那个额外的表单控件,所以我删除了它并且错误得到解决。

所以,我有这个代码:

<div class="dropdown-select-wrapper" *ngIf="contentData">
    <button mat-stroked-button [disableRipple]="true" class="mat-button" (click)="openSelect()" [ngClass]="{'only-icon': !contentData?.buttonText?.length}">
      <i *ngIf="contentData.iconClassInfo" class="dropdown-icon {{contentData.iconClassInfo.name}}"></i>
      <span class="button-text" *ngIf="contentData.buttonText">{{contentData.buttonText}}</span>
    </button>
    <mat-select class="small-dropdown-select" [formControl]="theFormControl" #buttonSelect (selectionChange)="onSelect(buttonSelect.selected)" (click)="$event.stopPropagation();">
      <mat-option *ngFor="let option of options" [ngClass]="{'selected-option': buttonSelect.selected?.value === option[contentData.optionsStructure.valName]}" [disabled]="buttonSelect.selected?.value === option[contentData.optionsStructure.valName] && contentData.optionSelectedWillDisable" [value]="option[contentData.optionsStructure.valName]">
        {{option[contentData.optionsStructure.keyName]}}
      </mat-option>
    </mat-select>
  </div>

这里我使用的是独立的 formControl,我遇到了我们正在谈论的错误,这对我来说毫无意义,因为我没有使用 formgroups 或 formarrays...它只是在我添加*ngIf 到 select 它自己,所以在它实际存在之前没有被使用。这就是解决我的问题的原因。

<mat-select class="small-dropdown-select" [formControl]="theFormControl" #buttonSelect (selectionChange)="onSelect(buttonSelect.selected)" (click)="$event.stopPropagation();" *ngIf="theFormControl">
          <mat-option *ngFor="let option of options" [ngClass]="{'selected-option': buttonSelect.selected?.value === option[contentData.optionsStructure.valName]}" [disabled]="buttonSelect.selected?.value === option[contentData.optionsStructure.valName] && contentData.optionSelectedWillDisable" [value]="option[contentData.optionsStructure.valName]">
            {{option[contentData.optionsStructure.keyName]}}
          </mat-option>
        </mat-select>

只有 WinMerge 让我找到了它(通过与可用版本的比较)。 我在 formGroupName 上遇到了案例问题。 这个词周围的括号会导致同样的问题。

创建formGroup时不小心输入了控件名称:

getFormGroup(dataItem: any): FormGroup {
    return new FormGroup({
        'Id': new FormControl(dataItem != null ? dataItem.Id : ''),
        'PsDepartmentId': new FormControl(dataItem != null ? dataItem.DepartmentId : '', Validators.required), //Accidentally used 'DepartmentId' on this line
        'IsActive': new FormControl(dataItem != null ? dataItem.IsActive : true)
    });
}

然后在 html 时失败了

          <kendo-dropdownlist id="ps-dpts-dropdown" [data]="psDepartments" textField="ConCatedName" valueField="Id"
          [formControl]="formGroup.get('DepartmentId')" [valuePrimitive]="true">                  
          </kendo-dropdownlist>

对我来说,问题是我在表单构建器中缺少字段名称:

  return this.fb.group({
      name: ['', [Validators.required]],
      latLong: ['', [Validators.required]],
      details: ['', [Validators.required]],
      // missing field name!
  });