TypeError: 在 Ng build 后无法读取空对象的 _rawValidators 属性

18

我是Angular的新手。我正在动态渲染一些字段到我的响应式表单中。当我使用一个模拟请求(即渲染正确,控制台没有错误)时,一切都很好地工作。但是,一旦我使用ng build并使用真正的后端,每个我动态渲染的字段都会出现错误:

main.js:1 ERROR TypeError: Cannot read property '_rawValidators' of null 

我找不到这个错误的任何背景信息。我很想听听您的想法。

更多背景

// these fields change with selection
this.datafields = [{
              dfId: 48,
              dfName: "Phone",
              dfType: "text",
              dfOptions: null,
              dfValue: ""
              },
              {
              dfId: 49,
              dfName: "Eval",
              dfType: "select",
              dfOptions: ["","Remote","Live"],
              df_value: "",
              }]

尝试在ngOnInit中使用TypeScript呈现(尝试了ngAfterViewInit但没有改善)

dfGroup = new FormGroup({})
...
...

 this.eyeForm = this.formBuilder.group({
      focus: ['', Validators.required],
 datafields: this.formBuilder.array([])
})

...
...

  if (this.datafields != null || this.datafields != undefined) {
  this.datafields.forEach((x:any) => {
          this.dfGroup.setControl(x.dfName, new FormControl(x.dfValue));
        });
  this.getDataFields.push(this.dfGroup);
  }

HTML看起来像下面这样:

 <div [formGroup]="dfGroup">
   <div class="row pt-2" *ngFor="let field of datafields; let i=index">
      <div class="col-4 d-flex align-items-center 13required">
         {{field.dfName}}&nbsp;
      </div>
      <div class="col-6">
         <mat-form-field *ngIf="field.dfType == 'text'" appearance="outline">
            <input
            matInput
            [type]="field.dfType"
            [formControlName]="field.dfName"
            required
            />
         </mat-form-field>
         <mat-form-field
            *ngIf="field.dfType == 'select'"
            appearance="outline"
            >
            <mat-select [formControlName]="field.dfName" placeholder="">
               <mat-option
               [value]="option"
               *ngFor="let option of field.dfOptions"
               >
               {{ option }}
               </mat-option>
            </mat-select>
         </mat-form-field>
      </div>
   </div>
</div>

您的错误栈中打印了 "main.js:1":尝试在构建/服务应用程序时停用优化选项,它将为您提供更多见解。关于您的错误,我也遇到过相同的情况,但情况有点不同:我正在将表单控件作为输入传递(即:<app-foo [formControl]="formControl"/>),但失败了,因为 formControl 似乎也被用作指令。使用输入别名解决了我的问题(即:<app-foo [fwdFormControl]="formControl"/>)。 - fservantdev
10个回答

21

在模拟我的模板并且打错了formControlName属性时,我遇到了这种情况。

<mycomponent formControlName="bogusfieldSpelledWrong" ...>

Angular为什么会显示这个错误可能与组件如何初始化/更改表单有关。


5
此外,似乎在模板中尝试添加具有FormGroup中不存在的formControlName的表单字段时会发生这种情况。 - Aaron Averett
@AaronAverett 我也有过类似的经历,而且...我很想知道我们如何在将来检测(或避免)这种情况。这个错误非常难以捉摸,容易犯错。 - undefined

9

这是由于视图中表单格式不正确造成的。

由于formArrayName、循环和formGroupName的错误排序导致了这个问题。

这个问题发生在表单 (控制器) 中。

form = <FormGroup>this.fb.group({
    hops: this.fb.array([
        this.fb.group({...}),
        ...
    ])
});

视图(错误)

<li class="asset" *ngFor="let control of hops.controls; let i = index;">
    <div formArrayName="hops">
        <div [formGroupName]="i">

视图(已更正)

<div formArrayName="hops">
    <li class="asset" *ngFor="let control of hops.controls; let i = index;">
        <div [formGroupName]="i">

6

这段内容涉及到formControlName。请检查你在ts文件和html文件中的表单控件名称。 对于嵌套组,可以使用formGroupName,然后使用formControlName。

this.yourForm = this.fb.group({
    name: [''],
    contact: this.fb.group({
      address: ['']
    }) 
})

<form [formGroup]="yourForm">
  <input type="text" formControlName="name" />
  <div formGroupName="contact">
    <input type="text" formControlName="address" />
  </div>
</form>

1
在我们的应用程序中,我们有一个缩小器,将类变量名称(在这种情况下,表单控件的名称)重命名为优化。这使得问题只出现在我们的生产环境中(在本地开发期间未执行优化)。
解决方案是直接引用控件实例而不是使用字符串,以便在角度模板中引用的变量与类局部变量一致地重命名。
之前:
  <div formGroupName="myInputGroup">
    <div formControlName="myInput">...</div>
  </div>

之后:

  <div [formGroup]="myInputGroup">
    <div [formControl]="myInputGroup.controls.myInput">...</div>
  </div>

0
在我的情况下,我在 HTML 中使用了一个 formControlName,但未在 TypeScript 文件中将其添加到表单中。

0

这个问题的另一个原因是您忘记分配 formGroup

错误的写法:

export class MyComponent{
 formGroup: FormGroup;
 ...
}

正确:

export class MyComponent{
 formGroup = new FormGroup({...});
 ...
}

0
对我来说,我有一个输入字段,里面没有`formControlName=""`。
而是
<input>...</input>

做:
<input formControlName="myInput"> ...</input>

-1

这可以通过添加formcontrolname值来解决。 类型错误会返回null,因为它在组件中没有找到值。

在您的Html文件中,formcontrolname必须与FormGroup的值相同。

例如:

<formControlName = 'username'>

this.formGroupName = this.formBuilder.group({
    username: ["", [Validators.required]],
    }) 
})

-1

我曾经遇到过类似的问题,你需要添加一个额外的 div 并设置属性 [formGroupName]="i"

最终代码如下:

<div [formGroup]="dfGroup">
    <div class="row pt-2" *ngFor="let field of datafields; let i=index">
        <div [formGroupName]="i">
            <div class="col-4 d-flex align-items-center 13required">
                {{field.dfName}}&nbsp;
            </div>
            <div class="col-6">
                <mat-form-field *ngIf="field.dfType == 'text'" appearance="outline">
                    <input matInput [type]="field.dfType" [formControlName]="field.dfName" required />
                </mat-form-field>
                <mat-form-field *ngIf="field.dfType == 'select'" appearance="outline">
                    <mat-select [formControlName]="field.dfName" placeholder="">
                        <mat-option [value]="option" *ngFor="let option of field.dfOptions">
                            {{ option }}
                        </mat-option>
                    </mat-select>
                </mat-form-field>
            </div>
        </div>
    </div>
</div>

-1
//html页面属性
formControlName="drugReproductive"
//ts文件属性
this.drugTypeTwo = new FormControl(0); this.drugTypeThree = new FormControl(0); this.drugTypeFour = new FormControl(0); this.drugTypeFive = new FormControl(0);
this.drugWithCanisterForm = this.fb.group({ drugAntineoplastic:this.drugAntineoplastic, drugNonAntineoplastic:this.drugNonAntineoplastic, drugReproductive:this.drugReproductive, drugTypeOne:this.drugTypeOne, drugTypeTwo:this.drugTypeTwo, drugTypeThree:this.drugTypeThree, drugTypeFour:this.drugTypeFour, drugTypeFive:this.drugTypeFive, configuration: this.configuration, deviceId:this.deviceId, deviceTypeId: this.deviceTypeId, isOtcExcluded: this.isOtcExcluded, isScheduleExcluded: this.isScheduleExcluded, isUnitOfUsageExcluded: this.isUnitOfUsageExcluded, unitOfUsageValue: this.unitOfUsageValue, canisterQuantity: this.canisterQuantity, canisterSize: this.canisterSize, searchText: this.searchText, scheduleExcludedValue: this.scheduleExcludedValue, nioshValue:this.nioshValue, superCellNo:this.superCellNo, lockingCellNo:this.lockingCellNo, superLockingCellNo:this.superLockingCellNo, isNioshExcluded:this.isNioshExcluded });
在我的情况下,这个问题出现了,因为我没有在表单对象中绑定formControllName属性。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接