Angular 4 Reactive Form无法读取未定义的属性

时间:2018-04-18 22:05:22

标签: angular forms validation angular-reactive-forms

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

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

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

1 个答案:

答案 0 :(得分:0)

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

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);