angular - 迎合具有空值的 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 文件中的电子邮件行上中断了。有什么我可以尝试的吗?
解决方案
代替
this.userReady.corporateContactChannels[0].value
和
this.userReady.corporateContactChannels[0]
? this.userReady.corporateContactChannels[0].value
: ''; // or whatever default value you want to use
唯一需要注意的另一项是您正在使用具有位置意义的索引,如果 api 中包含未定义的值,我希望这些索引得到保留/尊重。
推荐阅读
- php - 验证码不接受 Yii
- c# - Google Forms 上的 Webclient C# 从服务器返回 (405) Method Not Allowed
- java - 将 Excel 中的每个单元格数据转换为 XML 以存储到 DB
- java - 在java中动态设置类实例变量
- javascript - 使用 https.request 在 nodejs 中发送表单数据
- svn - 使用 SmartSVN 从 subversion 自动更新
- android - 需要 Android MVVM 示例架构项目
- php - MAILER ERROR: 无法实例化邮件功能,PHP 邮件程序
- android - Android 应用程序在某些设备上正常运行,某些设备应用程序崩溃
- android - 如何在Android中实现多按钮点击事件