文章内容

2022/5/25 14:17:18,作 者: 黄兵

Angular disable 导致无法获取值的解决办法

最近再使用 Angular 写后台的时候,出现 FormControl Disable() 无法获取值,下面是示例代码:

从后端获取值:

getCloudEmailSubscribeInfo() {
this.loading = true;
this.sub = this.phoneNumber.getEmailSubscribeInfo(this.data.id).subscribe(res => {
this.emailFormControl.setValue(res.email);
this.emailFormControl.disable();
this.confirmFormControl.setValue(res.confirmed ? 1 : 0);
}, error => {
this.snackBar.open(error.error.message ?? error.message, '关 闭', {
horizontalPosition: 'start',
verticalPosition: 'bottom',
});
}, () => {
this.loading = false;
});
}

更改之后保存,但是出现错误:

onConfirmEmailEdit($event): void {
if (!this.validateForm(this.emailSubscribeFormGroup)) {
return;
}
this.saveCloudLoading = true;
this.sub = this.phoneNumber.saveEmailSubscribeInfo(this.data.id, this.emailFormControl.value(),
this.confirmFormControl.value()).subscribe(res => {
if (res.returnResult === 'ok') {
this.dialogRef.close();
}
}, error => {
this.snackBar.open(error.error.message ?? error.message, '关 闭', {
horizontalPosition: 'start',
verticalPosition: 'bottom',
});
});
}

出错内容如下:

ERROR TypeError: this.emailFormControl.value is not a function

截图如下:


出现问题的原因:

FormControl Disable() 状态无法获取值。

解决方案:

出现 FormControl Disable() 无法获取值您可以使用 getRawValue() 而不是 value 属性。文档解释如下:

FormGroup 的聚合值,包括任何禁用的控件。

如果您想包含所有值而不考虑禁用状态,请使用此方法。否则,value 属性是获取组值的最佳方式。

我们可疑使用如下写法:

this.myForm.getRawValue()


参考资料:

1、How to disable form control but keep value


黄兵个人博客原创。

转载请注明出处:黄兵个人博客 - Angular disable 导致无法获取值的解决办法

分享到:

发表评论

评论列表