首页 > 解决方案 > 迎合具有空值的 Angular 表单

问题描述

我有以下表单初始化方法。我试图满足没有电子邮件价值的情况,即没有来自 api 的电子邮件价值。目前我收到以下错误:错误类型错误:无法读取未定义的属性“值”

  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 文件中的电子邮件行上中断了。有什么我可以尝试的吗?

标签: angular

解决方案


代替

this.userReady.corporateContactChannels[0].value 

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

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


推荐阅读