具有空值的Angular形式的餐饮

时间:2019-04-24 11:49:36

标签: angular

我有以下形式的初始化方法。我正在尝试满足没有电子邮件值的情况,即没有来自api的电子邮件值。当前,我收到以下错误: ERROR TypeError:无法读取未定义的属性'value'

  private initForm() {
    this._userService.getCurrentUserProfileData()
      .subscribe((user) => {
        this.userReady = user;
        console.log(this.userReady);
        this.userFormGroup = new FormGroup({
          firstName: new FormControl(this.userReady.firstname, [Validators.required, Validators.pattern('^[a-zA-Z]*$')]),
          lastName: new FormControl(this.userReady.lastname, [Validators.required, Validators.pattern('^[a-zA-Z]*$')]),
          email: new FormControl(this.userReady.corporateContactChannels[0].value, [Validators.required, Validators.email]),
          mobile: new FormControl(this.userReady.corporateContactChannels[1].value, [Validators.required, Validators.pattern('^[0-9]*$')]),
          workNumber: new FormControl(this.userReady.corporateContactChannels[2].value, [Validators.required, Validators.pattern('^[0-9]*$')]),
          role: new FormControl({value: this.storeService.setStoreData().profile.role, disabled: true} , Validators.required)
        });
      }, (error) => {
        this._errorService.openErrorPopup('Failed to get profile data.');
      }
    );
  }

我在html表单上尝试了一个* ngIf,但是它似乎在ts文件中的电子邮件行上断开了。有什么可以尝试的吗?

2 个答案:

答案 0 :(得分:4)

替换

this.userReady.corporateContactChannels[0].value 

this.userReady.corporateContactChannels[0] 
  ? this.userReady.corporateContactChannels[0].value 
  : ''; // or whatever default value you want to use

唯一需要注意的另一项是您正在使用具有位置重要性的索引,我希望如果api中包含未定义的值,这些索引将被保留/尊重。

答案 1 :(得分:1)

如果您只想避免这种情况,请执行以下操作:


this.userFormGroup = new FormGroup({
  ...
  email: new FormControl(
            this.userReady && this.userReady.corporateContactChannels[0] 
              ? this.userReady.corporateContactChannels[0].value 
              : null, 
            [Validators.required, Validators.email]),
  mobile: ...
});