【问题标题】:Angular 4 Reactive Form cannot read property invalid of undefinedAngular 4 Reactive Form无法读取未定义的无效属性
【发布时间】:2023-03-20 14:45:01
【问题描述】:

我正在使用我的组件中定义的反应形式:

ngOnInit() {
  this.client = this.params.get('client')

  this.profile_form = this.fb.group({
    id: [this.client.id],
    name: [this.client.name, [Validators.required]],
    address: [this.client.address],
    target_weight: [this.client.target_weight, [Validators.required]],
    target_weight2: [this.client.target_weight2, [Validators.required]],
    referred_by: [this.client.referred_by]
  })

}

在我的模板中我有:

<div class="row" padding-left>
  <div class="col" no-padding>
    <ion-item class="better-validation" [class.invalid]="target_weight.invalid && profile_form.dirty">
      <ion-label floating>Target Weight (High)</ion-label>
      <ion-input type="number" formControlName="target_weight"></ion-input>
    </ion-item>
    <div padding-left *ngIf="target_weight.invalid && profile_form.dirty" class=" text-danger">
      High target weight is required
    </div>
  </div>
  <div class="col" no-padding padding-right>

    <!-- Line causing the error -->
    <ion-item class="better-validation" [class.invalid]="target_weight2.invalid && profile_form.dirty">
      <ion-label floating>Target Weight (Low) {{ target}}</ion-label>
      <ion-input type="number" formControlName="target_weight2"></ion-input>
    </ion-item>
  </div>
</div>

如果出现问题,我不明白为什么 target_weight 的验证不会引发错误。 this.client.target_weightthis.client.target_weight2 都是 null

有人知道这里出了什么问题吗?

【问题讨论】:

  • this.params 的值是多少?
  • 参数中有大量信息。我真的很困惑为什么所有其他字段中的 1 个字段(为了简洁起见,我没有包括其他字段)导致错误

标签: angular forms validation angular-reactive-forms


【解决方案1】:

您必须首先使用其默认值定义表单,然后修补您的对象值。

this.profile_form = this.fb.group({
id: [0],
name: ['', [Validators.required]],
address: [''],
target_weight: ['', [Validators.required]],
target_weight2: ['', [Validators.required]],
referred_by: ['']});

this.profile_form.patchValue(this.client);

【讨论】:

  • 这无法解释为什么只有 1 个字段会导致错误
猜你喜欢
  • 2018-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-26
  • 2018-05-09
  • 1970-01-01
相关资源
最近更新 更多